Reputation: 449
If I call csv.Read()
on a CSV file that is completely empty, I get an exception. Is there a way to check the CSV without having to fall back on a 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;
}
Upvotes: 1
Views: 7130
Reputation: 1185
You can use File.Exists
on the source csvfile path.
if (File.Exists("csvfile"))
{
//process
}
Edit: Apologies, misread your post, you would indeed need to combine this with the answer above to check for an empty (but existing) file.
Upvotes: -1
Reputation: 75
Use FileInfo
if (new FileInfo("yourfilename").Length == 0)
{
//Do something here
}
else
{
//Do something else here
}
You should also probably check to make sure the file exists because it will throw a FileNotFoundException if the file doesn't exist.
Upvotes: 2
Reputation: 6347
You can simply check if file has zero length
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;
}
}
Upvotes: 3