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?
Sometimes using libraries are cool when you do not want to reinvent the wheel, but in this case one can do the same job with fewer lines of code and easier to read compared to using libraries. Here is a different approach which I find very easy to use.
CSV can get complicated real fast.
Use something robust and well-tested:
FileHelpers: www.filehelpers.net
I use this here:
http://www.codeproject.com/KB/database/GenericParser.aspx
Last time I was looking for something like this I found it as an answer to this question.
Don't reinvent the wheel. Take advantage of what's already in .NET BCL.
Microsoft.VisualBasic
(yes, it says VisualBasic but it works in C# just as well - remember that at the end it is all just IL)Microsoft.VisualBasic.FileIO.TextFieldParser
class to parse CSV fileHere is the sample code:
It works great for me in my C# projects.
Here are some more links/informations:
First of all need to understand what is CSV and how to write it.
/r/n
) is next "table" row.\t
or,
/r/n
sybols (cell must to start with quotes symbol and ends with this symbol in this case)The easiest way for C#/Visual Basic to work with CSV files is to use standard
Microsoft.VisualBasic
library. You just need to add needed reference, and the following string to your class:Yes, you can use it in C#, don't worry. This library can read relatively big files and supports all of needed rules, so you will be able to work with all of CSV files.
Some time ago I had wrote simple class for CSV read/write based on this library. Using this simple class you will be able to work with CSV like with 2 dimensions array. You can find my class by the following link: https://github.com/ukushu/DataExporter
Simple example of using:
I recommend CsvHelper from Nuget.
(Adding a reference to Microsoft.VisualBasic just doesn't feel right, it's not only ugly, it's probably not even cross-platform.)