Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 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\""
like image 590
Callum Watkins Avatar asked Mar 24 '16 20:03

Callum Watkins


2 Answers

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"
like image 142
Callum Watkins Avatar answered Oct 15 '22 22:10

Callum Watkins


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);
            }
        }
    }
}
like image 40
ManoDestra Avatar answered Oct 15 '22 21:10

ManoDestra