Problem
I’m working on a basic import application that requires reading a CSV file, displaying the result in a DataGrid, and displaying the corrupted lines of the CSV file in another grid. Show the lines in another grid that are shorter than 5 values, for example. I’m attempting to do it in the following manner:
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])
});
}
However, working with arrays in this scenario is really tough. Is there a more efficient way to divide the values?
Asked by ilkin
Solution #1
Don’t start from scratch. Use the features of.NET BCL that are already available.
Here’s some code to get you started:
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 performs admirably in my C# projects.
Here are some more resources/links:
Answered by David Pokluda
Solution #2
Nuget’s CsvHelper comes highly recommended.
PS: I apologize for making a reference to Microsoft in other higher upvoted answers. VisualBasic is comprised of the following components:
Answered by knocte
Solution #3
There are numerous different csv formats, in my experience. Particularly, how they deal with escaping quotes and delimiters within a field.
I’ve encountered the following variations:
I’ve tried many of the existing csv parsers, but none of them can handle the variants I’ve encountered. It’s also difficult to tell which escape variants the parsers allow from the documentation.
I currently use either the VB TextFieldParser or a custom splitter in my projects.
Answered by adrianm
Solution #4
When you don’t want to reinvent the wheel, libraries can be useful, but in this situation, you can achieve the same result with fewer lines of code and a more readable codebase. Here’s a another method that I find incredibly simple to utilize.
using (StreamReader reader = new StreamReader(fileName))
{
string line;
while ((line = reader.ReadLine()) != null)
{
//Define pattern
Regex CSVParser = new Regex(",(?=(?:[^\"]*\"[^\"]*\")*(?![^\"]*\"))");
//Separating columns to array
string[] X = CSVParser.Split(line);
/* Do something with X */
}
}
Answered by Mana
Solution #5
CSV can quickly get difficult. Use something dependable and tried and true: FileHelpers can be found at www.filehelpers.net.
Answered by Keith Blows
Post is based on https://stackoverflow.com/questions/3507498/reading-csv-files-using-c-sharp