1

如果我调用csv.Read()一个完全为空的 CSV 文件,则会出现异常。有没有办法检查 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;
}
4

3 回答 3

3

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

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;
  }

}
于 2015-07-29T15:48:33.110 回答
2

使用文件信息

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

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

于 2015-07-29T15:51:29.217 回答
-1

您可以File.Exists在源 csvfile 路径上使用。

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

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

于 2015-07-29T15:48:57.053 回答