I'm surprised that I haven't seen anything about this on here (or maybe I missed it). When parsing a CSV file, if there are rows with no data, how can/should that be handled? I'm not talking about blank rows, but empty rows, for example:
ID,Name,Quantity,Price
1,Stuff,2,5
2,Things,1,2.5
,,,
,,,
,,,
I am using TextFieldParser to handle commas in data, multiple delimiters, etc. The two solutions I've thought of is to either use ReadLine instead of ReadFields, but that would remove the benefits of using the TextFieldParser, I'd assume, because then I'd have to handle commas a different way. The other option would be to iterate through the fields and drop the row if all of the fields are empty. Here's what I have:
dttExcelTable = new DataTable();
using (TextFieldParser parser = new TextFieldParser(fileName))
{
parser.Delimiters = new string[] { ",", "|" };
string[] fields = parser.ReadFields();
if (fields == null)
{
return null;
}
foreach (string columnHeader in fields)
{
dttExcelTable.Columns.Add(columnHeader);
}
while (true)
{
DataRow importedRow = dttExcelTable.NewRow();
fields = parser.ReadFields();
if (fields == null)
{
break;
}
for (int i = 0; i < fields.Length; i++)
{
importedRow[i] = fields[i];
}
foreach (var field in importedRow.ItemArray)
{
if (!string.IsNullOrEmpty(field.ToString()))
{
dttExcelTable.Rows.Add(importedRow);
break;
}
}
}
}