read a csv from a string in csharp

To read a CSV from a string in C#, you can use the TextFieldParser class from the Microsoft.VisualBasic.FileIO namespace.

Here's an example code snippet that shows how to read a CSV from a string and convert it to a List<string[]> where each string array represents a row in the CSV:

main.cs
using Microsoft.VisualBasic.FileIO;
using System.Collections.Generic;
using System.IO;

public static List<string[]> ReadCsvFromString(string csvString)
{
    var result = new List<string[]>();

    // convert the string to a stream
    using (var stream = new MemoryStream())
    using (var writer = new StreamWriter(stream))
    {
        writer.Write(csvString);
        writer.Flush();
        stream.Position = 0;

        // read the CSV from the stream using TextFieldParser
        using (var parser = new TextFieldParser(stream))
        {
            parser.TextFieldType = FieldType.Delimited;
            parser.SetDelimiters(",");

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

    return result;
}
798 chars
32 lines

You can call this method by passing in your CSV string:

main.cs
string csvString = "Name,Age,Gender\nJohn,30,Male\nMary,25,Female\n";
List<string[]> csvRows = ReadCsvFromString(csvString);
125 chars
3 lines

This will give you a List<string[]> containing three string arrays, each representing a row in the CSV. You can loop through the list and access each column value by index:

main.cs
foreach (var row in csvRows)
{
    string name = row[0];
    int age = int.Parse(row[1]);
    string gender = row[2];

    // do something with the values...
}
160 chars
9 lines

gistlibby LogSnag