131

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

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
mrblah
  • 99,669
  • 140
  • 310
  • 420
  • 81
    I beg to differ. This is definitely a constructive question and the first result on google for `.net csv library`. Evidence, though anecdotal, for my claim is that this question has been viewed more than 22000 times in the past six years. – shovavnik Jan 03 '16 at 15:14
  • 6
    true said - first hit on google – Robetto Sep 20 '16 at 08:02
  • There is a nice speed comparison: https://www.joelverhagen.com/blog/2020/12/fastest-net-csv-parsers – Neil May 25 '21 at 11:50

5 Answers5

119

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.

George Stocker
  • 57,289
  • 29
  • 176
  • 237
Josh Close
  • 22,935
  • 13
  • 92
  • 140
  • 3
    Thanks, Josh. I gave this a go, and it was both fast and memory efficient. I think the documentation could be improved a bit for first-time users, but it was definitely sufficient. – Sam Dec 06 '16 at 22:08
  • 1
    Is there a way to use this library without a custom type so that I can just iterate through my table grid (custom) and write out header and then pass each row field? I'm just looking for a way to prevent errors in the files (escaping properly etc). – u84six Oct 09 '18 at 21:09
  • Yes. You can use `WriteField`. Check the docs here https://joshclose.github.io/CsvHelper/ – Josh Close Oct 10 '18 at 01:06
  • 1
    @Zimano Not true. You can read individual fields or even just get a string array for the row. Check out the documentation. https://joshclose.github.io/CsvHelper – Josh Close Oct 04 '19 at 15:55
  • @JoshClose Oh, that's good to hear, thanks! I only checked out the getting started guide here: https://joshclose.github.io/CsvHelper/getting-started#reading-a-csv-file and it didn't include my use case. I should've looked further, my apologies. However, on that page it does say that using a mapping of some kind is the recommended way to use `CsvHelper`. Perhaps it could offer some alternative read strategies on that spot? I've deleted my original remark by the way, as it's now irrelevant :-) – Zimano Oct 05 '19 at 10:42
  • Sure. Submit an issue on GitHub to add it to the documentation and it'll get added – Josh Close Oct 05 '19 at 17:00
23

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.

Reed Copsey
  • 554,122
  • 78
  • 1,158
  • 1,373
  • 6
    I always wondered why it was in the Microsoft.VisualBasic assembly... Did MS think that C# developers didn't use CSV ? – Thomas Levesque Dec 21 '09 at 17:36
  • 4
    @Thomas: especially since a lot of C# developers cringe at the thought of including a VisualBasic assembly in their projects –  Dec 21 '09 at 17:42
  • 2
    Yeah - there are lots of nice "goodies" in there. I think it's more because VB has some language constructs that weren't really considered in the framework originally, but they would never have been able to get VB6 users across without implementing them. The Devices and ApplicationServices namespaces have all sorts of useful things. – Reed Copsey Dec 21 '09 at 17:44
  • 21
    @Roboto,any C# developer that cringes at referencing Microsoft.VisualBasic in their project is an ignorant language snob. Even worse they don't understand .NET at all. – Ash Dec 30 '09 at 02:18
  • 3
    Another VB assembly gem is CopyDirectory: http://stackoverflow.com/questions/58744/best-way-to-copy-the-entire-contents-of-a-directory-in-c –  Dec 19 '10 at 23:01
  • This. TextFieldPasrser is what we use. And for CSV-**writing** we wrote our own tiny open-source component that takes care of escaping line-breaks, quotes, commas, optionally trims lines for Excel compatibility etc. https://github.com/jitbit/CsvExport – Alex from Jitbit Jul 10 '17 at 07:59
  • @Ash VB libraries are not going to be consumable in a .NET Core context, though, right? Specifically code in the .FileIO namespace – Steve Boniface Feb 28 '19 at 16:55
17

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();
            }
        };
    }
}
Matze
  • 5,100
  • 6
  • 46
  • 69
  • 2
    This is my favourite. Great little library. – Alex Dec 21 '09 at 17:24
  • but can't it write also? – mrblah Dec 21 '09 at 17:25
  • I know - I have used it for the past two years - no issues! –  Dec 21 '09 at 17:25
  • 2
    Writing CSV is easy - just use a normal text output method, and separate by commas. You really only need a library/custom handler for reading... – Reed Copsey Dec 21 '09 at 17:26
  • 11
    @Reed: it is not too trivial if you want to have commas and quotation marks escaped correctly. I'm not even sure if there is a standardization for this, but is is very common to do it. – Stefan Steinegger Dec 21 '09 at 18:03
  • 28
    Writing CSV is a bit more complex than that. If the data you want expressed in the CSV file contains commas or new lines, you need to surround the data with quotation marks. If there's a quotation mark in the newly quotation-marked data, then you need to escape the quotation mark with double quotation marks. You could certainly code that logic yourself but it would be nice for a library to do it for you. – Tinister Dec 21 '09 at 18:08
  • @Tinister: Sure, it was a simple example - but where's the standardization? –  Dec 21 '09 at 18:15
  • 4
    The standardization is RFC 4180. http://tools.ietf.org/html/rfc4180 – Josh Close Sep 04 '13 at 17:09
  • This answer is incorrect! It fo not cover escaping! – Bogdan Mart Feb 09 '18 at 01:08
  • This answer doesn't work for values that contain quotation marks. You need to double them up. – rom99 Mar 25 '20 at 12:20
7

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

Try FileHelpers

Marcos Meli
  • 3,468
  • 24
  • 29
Murph
  • 9,985
  • 2
  • 26
  • 41
  • Well, I did but for some strange reason FileHelpers broke down randomly. Furthermore, the FileHelpers library has not been in development for a long time. – Erik Schierboom Feb 04 '11 at 09:02
  • 1
    FileHelpers are actively developed now, see the [GitHub](https://github.com/MarcosMeli/FileHelpers). – xmedeko Apr 07 '16 at 06:55
3

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.

Bernard Vander Beken
  • 4,848
  • 5
  • 54
  • 76
Alex
  • 3,099
  • 6
  • 41
  • 56