Are there any CSV readers/writer libraries in C#?

C#Csv

C# Problem Overview


Are there any CSV readers/writer libraries in C#?

C# Solutions


Solution 1 - C#

Try CsvHelper. It's as easy to use as FastCsvReader and does writing also. I've been very happy with FastCsvReader in the past, but I needed something that does writing also, and wasn't happy with FileHelpers.

Reading:

var csv = new CsvReader( stream );
var myCustomTypeList = csv.GetRecords<MyCustomType>();

Writing:

var csv = new CsvWriter( stream );
csv.WriteRecords( myCustomTypeList );

Full Disclosure: I am the author of this library.

Solution 2 - C#

There are a couple of options, right in the framework itself.

One of the easiest is to Reference Microsoft.VisualBasic, then use TextFieldParser. It is a fully functional CSV reader in the core framework.

Another good alternative is to use datasets to read CSV files.

Solution 3 - C#

Sebastien Lorion has a great CSV reader on CodeProject called A Fast CSV Reader. Probably one of the best for C# and it's free.

As far as writing, just use StreamWriter.

Here is some boilerplate code for writing a DataGridView to a file:

private void exportDGVToCSV(string filename)
{
    if (dataGridView1.Columns.Count != 0) 
    {    
        using (Stream stream = File.OpenWrite(filename))
        {
            stream.SetLength(0);
            using (StreamWriter writer = new StreamWriter(stream))
            {
                // loop through each row of our DataGridView
                foreach (DataGridViewRow row in dataGridView1.Rows) 
                {
                    string line = string.Join(",", row.Cells.Select(x => $"{x}"));
                    writer.WriteLine(line);
                }

                writer.Flush();
            }
        };
    }
}

Solution 4 - C#

Yes - though I assume you're actually asking for specifics?

Try FileHelpers

Solution 5 - C#

There are dozens.

http://www.filehelpers.net/ is one of the most common.

I should say that I find Filehelpers restrictive in some scenarios, and instead use The Fast CSV Reader. In my experience, if you don't know the format of your CSV file or import mapping until runtime - this is the better library to use.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionmrblahView Question on Stackoverflow
Solution 1 - C#Josh CloseView Answer on Stackoverflow
Solution 2 - C#Reed CopseyView Answer on Stackoverflow
Solution 3 - C#user195488View Answer on Stackoverflow
Solution 4 - C#MurphView Answer on Stackoverflow
Solution 5 - C#AlexView Answer on Stackoverflow