Skip to main content
 首页 » 编程设计

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

2024年02月05日36jillzhang

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