TextFieldParser parse CSV from string not file

Viewed 10301

Using a TextFieldParser from Microsoft.VisualBasic.FileIO it is possible to parse a CSV file like below:

using (TextFieldParser parser = new TextFieldParser(CSVPath))
{
    parser.TextFieldType = FieldType.Delimited;
    parser.SetDelimiters(",");
    parser.HasFieldsEnclosedInQuotes = true;
    while (!parser.EndOfData) { string[] fields = parser.ReadFields(); }
}

However this relies on initialising the TextFieldParser with a CSV file path. Is it possible to have the same effect but while passing in a string that contains the data record itself?

For example with a CSV data record with the value of Data1,6.5,"Data3 ""MoreData""" (note the last data enclosed in quotes because of the escaped quotation marks) saved in a string variable, could I convert the data to a string array like this:

[0] = "Data1"
[1] = "6.5"
[2] = "Data3 \"MoreData\""
3 Answers

Using TextFieldParser is the easiest, simplest way to go and as said in accepted answer, you totally can instantiate it from a stream.

Despite that, I would like to complete the accepted answer with a valuable piece of information for all of you who landed here after a G**gle search :

I found a really simple parser reading CSV data with this piece of code :

var res = new List<string[]>();

using (TextFieldParser parser = new TextFieldParser(filepath))
{
    parser.CommentTokens = new string[] { "#" };
    parser.SetDelimiters(new string[] { ";" });
    parser.HasFieldsEnclosedInQuotes = true;

    // Skip over header line.
    parser.ReadLine();

    while (!parser.EndOfData)
    {
        res.Add(parser.ReadFields());
    }
}

be really carefull with parser.ReadLine() as it may give unwanted result if at least one of your header's fields contains CRLF. In such a case your first read line will contain the remaining part of your headers right after the first CRLF.

So please note that it will be much better to read your whole file with ReadFields which take great care of well formated fields (cf. the CSV RFC at https://www.rfc-editor.org/rfc/rfc4180) , including headers, then ignoring your first line if needed.

4180 RFC is complete enough to give you the way to go if you want to implement a proper CSV writer too.

Have fun with CSV guys.

Related