Callum Watkins Callum Watkins - 2 months ago 34
C# Question

TextFieldParser parse CSV from string not file

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

You can also instantiate TextFieldParser from a Stream or from a TextReader. It doesn't have to be a string path. So, you can stream it whatever you like really, so long as you can get it into a stream. Could simply be a MemoryStream.

https://msdn.microsoft.com/en-us/library/microsoft.visualbasic.fileio.textfieldparser%28v=vs.110%29.aspx

E.g.

using (var stream = new MemoryStream())
{
    var input = "A, B, C, D\r\n";
    input += "Jeremy,Paul,Linda,Joe\r\n";
    var bytes = System.Text.Encoding.Default.GetBytes(input);
    stream.Write(bytes, 0, bytes.Length);
    stream.Seek(0, SeekOrigin.Begin);
    using (var parser = new TextFieldParser(stream))
    {
        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);
            }
        }
    }
}