Are there any CSV readers/writer libraries in C#? [closed]
Asked Answered
T

5

136

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

Telesthesia answered 21/12, 2009 at 17:16 Comment(0)
B
120

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.

Blintz answered 19/1, 2010 at 16:6 Comment(5)
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).Pterosaur
Yes. You can use WriteField. Check the docs here joshclose.github.io/CsvHelperBlintz
@Brandebrandea Not true. You can read individual fields or even just get a string array for the row. Check out the documentation. joshclose.github.io/CsvHelperBlintz
@JoshClose Oh, that's good to hear, thanks! I only checked out the getting started guide here: joshclose.github.io/CsvHelper/… 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 :-)Brandebrandea
Sure. Submit an issue on GitHub to add it to the documentation and it'll get addedBlintz
S
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.

Spendthrift answered 21/12, 2009 at 17:23 Comment(7)
I always wondered why it was in the Microsoft.VisualBasic assembly... Did MS think that C# developers didn't use CSV ?Lock
@Thomas: especially since a lot of C# developers cringe at the thought of including a VisualBasic assembly in their projectsAforesaid
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.Spendthrift
@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.Interlaken
Another VB assembly gem is CopyDirectory: #59244Glarus
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. github.com/jitbit/CsvExportSarita
@Interlaken VB libraries are not going to be consumable in a .NET Core context, though, right? Specifically code in the .FileIO namespaceDacy
A
19

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();
            }
        };
    }
}
Aforesaid answered 21/12, 2009 at 17:22 Comment(10)
This is my favourite. Great little library.Roster
but can't it write also?Telesthesia
I know - I have used it for the past two years - no issues!Aforesaid
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...Spendthrift
@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.Concupiscent
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.Breannabreanne
@Tinister: Sure, it was a simple example - but where's the standardization?Aforesaid
The standardization is RFC 4180. tools.ietf.org/html/rfc4180Blintz
This answer is incorrect! It fo not cover escaping!Pierrette
This answer doesn't work for values that contain quotation marks. You need to double them up.Intractable
A
7

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

Try FileHelpers

Architectonic answered 21/12, 2009 at 17:20 Comment(2)
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.Hoffmann
FileHelpers are actively developed now, see the GitHub.Ilana
R
4

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.

Roster answered 21/12, 2009 at 17:21 Comment(3)
We use filehelpers also.Dorison
I have found FileHelpers to be a nuisance to configure. FastCsvReader was a lot easier to use.Blintz
+1 for FastCsvReader. Excellent performance. But it's a mainly a reader/parser. Not A writer.Terret

© 2022 - 2024 — McMap. All rights reserved.