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

时间:2015-07-29 15:41:40

标签: c# winforms csv csvhelper

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

3 个答案:

答案 0 :(得分: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;
  }

}

答案 1 :(得分:2)

使用FileInfo

target="_self"

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

答案 2 :(得分:0)

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

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

编辑:道歉,误读了你的帖子,你确实需要将它与上面的答案结合起来检查一个空的(但现有的)文件。