Search code examples
c#csv

Reading CSV files using C#


I'm writing a simple import application and need to read a CSV file, show result in a DataGrid and show corrupted lines of the CSV file in another grid. For example, show the lines that are shorter than 5 values in another grid. I'm trying to do that like this:

StreamReader sr = new StreamReader(FilePath);
importingData = new Account();
string line;
string[] row = new string [5];
while ((line = sr.ReadLine()) != null)
{
    row = line.Split(',');

    importingData.Add(new Transaction
    {
        Date = DateTime.Parse(row[0]),
        Reference = row[1],
        Description = row[2],
        Amount = decimal.Parse(row[3]),
        Category = (Category)Enum.Parse(typeof(Category), row[4])
    });
}

but it's very difficult to operate on arrays in this case. Is there a better way to split the values?


Solution

  • Don't reinvent the wheel. Take advantage of what's already in .NET BCL.

    • add a reference to the Microsoft.VisualBasic (yes, it says VisualBasic but it works in C# just as well - remember that at the end it is all just IL)
    • use the Microsoft.VisualBasic.FileIO.TextFieldParser class to parse CSV file

    Here is the sample code:

    using (TextFieldParser parser = new TextFieldParser(@"c:\temp\test.csv"))
    {
        parser.TextFieldType = FieldType.Delimited;
        parser.SetDelimiters(",");
        while (!parser.EndOfData) 
        {
            //Processing row
            string[] fields = parser.ReadFields();
            foreach (string field in fields) 
            {
                //TODO: Process field
            }
        }
    }
    

    It works great for me in my C# projects.

    Here are some more links/informations: