Reputation: 137594
I use Microsoft.VisualBasic.FileIO.TextFieldParser to parse csv files.
I'd now know like to export some data to csv format. For consistency on the difficult csv behaviours (quoting, escaping, etc) I'd like to use the same class or a similar one - ideally in the standard library, so that I can trust to be compatible.
How can I do that?
Edit: My data to export is List<List<string>>
Upvotes: 1
Views: 2560
Reputation: 22876
The characters that are escaped in standard CSV are Tab, CR, LF, double quote, and comma:
char[] chars = { '\t', '\r', '\n', '\"', ',' };
if (stringField.IndexOfAny(chars) >= 0)
{
stringField = '\"' + stringField.Replace("\"", "\"\"") + '\"'; // replace " with ""
}
It can easily be tested with Excel or copying from a DataGridView
control.
Upvotes: 1
Reputation: 499042
TextFieldParser
can only be used to read structured text files, such as CSV files.
In order to write, I suggest using File Helpers, which can also be used to read CSV files (so can be an altogether replacement).
Upvotes: 1