检查CSV文件是否为空/避免抛出异常
本文关键字:抛出异常 CSV 文件 是否 检查 | 更新日期: 2023-09-27 18:05:18
如果我在一个完全为空的CSV文件上调用csv.Read()
,我会得到一个异常。是否有一种方法可以检查CSV而不必回到Catch块上?
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;
}
}
使用FileInfo
if (new FileInfo("yourfilename").Length == 0)
{
//Do something here
}
else
{
//Do something else here
}
您可能还应该检查文件是否存在,因为如果文件不存在,它将抛出FileNotFoundException
您可以在源csvfile路径上使用File.Exists
if (File.Exists("csvfile"))
{
//process
}
编辑:抱歉,误解了你的帖子,你确实需要将此与上面的答案结合起来检查空(但存在)文件。