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

Checking if CSV file is empty / avoiding having an exception be thrown

如果我在一个完全空的 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;
  }

}

您可以在源 csv 文件路径上使用 File.Exists

if (File.Exists("csvfile"))
{
   //process
}

编辑:抱歉,误读了您的 post,您确实需要将其与上面的答案结合起来检查一个空的(但存在的)文件。

使用文件信息

if (new FileInfo("yourfilename").Length == 0)
{
//Do something here
}
else
{
//Do something else here
}

您可能还应该检查以确保文件存在,因为如果文件不存在,它将抛出 FileNotFoundException。