简体   繁体   中英

How to write csv format compatible with Microsoft.VisualBasic.FileIO.TextFieldParser?

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>>

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).

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM