Search code examples
c#.netcsvcsvhelper

Read CSV from variable using CsvHelper (or similar library)


I've got a function that makes something equivalent to a web request, and it returns a formatted CSV. My goal is to now import this data into CsvHelper. However, I can't seem to get CSVParser to read from static text, only from a stream.

I could write the output to a file then read it back, but I feel that doesn't make much sense here.

I'm not tied down at all to CsvHelper, however I can't seem to find a CSV library that supports this behavior. How should I do this?

var csvString = functionThatReturnsCsv()
/* as string:
columnA,columnB
dataA,dataB
*/

// my goal
???.parse(csvString)

Solution

  • You can convert the string to a Stream in-memory and then use that as the source for your CSV reader:

    public static Stream StringAsStream(string value)
    {
        return StringAsStream(value, System.Text.Encoding.UTF8);
    }
    
    public static Stream StringAsStream(string value, System.Text.Encoding encoding)
    {
        var bytes = encoding.GetBytes(value);
        return new MemoryStream(bytes);
    }
    

    Usage:

    using (var stream = StringAsStream("hello"))
    {
        // csv reading code here
    }
    

    or

    using (var stream = StringAsStream("hello", Encoding.Ascii))
    {
        // csv reading code here
    }
    

    Try it online

    Note If you are reading from a source that can return a Stream (like a web request), you should use that Stream rather than doing this.