TextFieldParser parse CSV from string not file

Callum Watkins picture Callum Watkins · Mar 24, 2016 · Viewed 9.4k times · Source

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

Answer

Callum Watkins picture Callum Watkins · Mar 24, 2016

A StringReader that contains the raw string can be passed into a new TextFieldParser and processed in the same way.

StringReader sr = new StringReader("Data1,6.5,\"Data3,\"\"MoreData\"\"\"");
using (var parser = new TextFieldParser(sr))
{
    parser.TextFieldType = FieldType.Delimited;
    parser.SetDelimiters(",");
    parser.HasFieldsEnclosedInQuotes = true;
    while (!parser.EndOfData)
    {
        Console.WriteLine("Line:");
        var fields = parser.ReadFields();
        foreach (var field in fields)
        {
            Console.WriteLine("\tField: " + field);
        }
    }
}

Output to console:

Line:
    Field: Data1
    Field: 6.5
    Field: Data3,"MoreData"