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 any better way to split the values?
To complete the previous answers, one may need a collection of objects from his CSV File, either parsed by the
TextFieldParser
or thestring.Split
method, and then each line converted to an object via Reflection. You obviously first need to define a class that matches the lines of the CSV file.I used the simple CSV Serializer from Michael Kropat found here: Generic class to CSV (all properties) and reused his methods to get the fields and properties of the wished class.
I deserialize my CSV file with the following method:
My experience is that there are many different csv formats. Specially how they handle escaping of quotes and delimiters within a field.
These are the variants I have ran into:
I have tried many of the existing csv parsers but there is not a single one that can handle the variants I have ran into. It is also difficult to find out from the documentation which escaping variants the parsers support.
In my projects I now use either the VB TextFieldParser or a custom splitter.
Another one to this list, Cinchoo ETL - an open source library to read and write CSV files
For a sample CSV file below
Quickly you can load them using library as below
If you have POCO class matching the CSV file
You can use it to load the CSV file as below
Please check out articles at CodeProject on how to use it.
Disclaimer: I'm the author of this library