TextFieldParser parse CSV from string not file
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"
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);
}
}
}
}