gpt4 book ai didi

c# - 检查 CSV 文件是否为空/避免抛出异常

转载 作者:太空宇宙 更新时间:2023-11-03 21:19:38 26 4
gpt4 key购买 nike

如果我在一个完全为空的 CSV 文件上调用 csv.Read(),我会得到一个异常。有没有一种方法可以检查 CSV 而不必退回到 Catch block ?

var csv = new CsvReader(csvFile);

try
{
while (csv.Read())
{
// process the CSV file...
}
}
catch (CsvReaderException)
{
// Handles this error (when attempting to call "csv.Read()" on a completely empty CSV):
// An unhandled exception of type 'CsvHelper.CsvReaderException' occurred in CsvHelper.dll
// Additional information: No header record was found.
MessageBox.Show(MessageBoxErrorMessageExpectedColumns, MessageBoxErrorMessageCaption, MessageBoxButtons.OK, MessageBoxIcon.Error);
return null;
}

最佳答案

您可以简单地检查文件长度是否为零

var csvFileLenth = new System.IO.FileInfo(path).Length;

if( csvFileLenth != 0)
{
try
{
while (csv.Read())
{
// process the CSV file...
}
}
catch (CsvReaderException)
{
// Handles this error (when attempting to call "csv.Read()" on a completely empty CSV):
// An unhandled exception of type 'CsvHelper.CsvReaderException' occurred in CsvHelper.dll
// Additional information: No header record was found.
MessageBox.Show(MessageBoxErrorMessageExpectedColumns, MessageBoxErrorMessageCaption, MessageBoxButtons.OK, MessageBoxIcon.Error);
return null;
}

}

关于c# - 检查 CSV 文件是否为空/避免抛出异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31705116/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com