Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CsvHelper not writing data to memory stream

Tags:

Having some problems with CsvHelper and writing to a memory stream. I've tried flushing the stream writer and setting positions and everything else tried. I figure I've narrowed it down to a really simple test case that obviously fails. What am I doing wrong here?

public OutputFile GetTestFile()
{
    using (var ms = new MemoryStream())
    using (var sr = new StreamWriter(ms))
    using (var csv = new CsvWriter(sr))
    {
        csv.WriteField("test");
        sr.Flush();

        return new OutputFile
        {
            Data = ms.ToArray(),
            Length = ms.Length,
            DataType = "text/csv",
            FileName = "test.csv"
        };
    }
}

[TestMethod]
public void TestWritingToMemoryStream()
{
    var file = GetTestFile();
    Assert.IsFalse(file.Data.Length == 0);
}

Editing the correct answer in for people googling as this corrected code actually passes my test. I have no idea why writing to a StringWriter then converting it to bytes solves all the crazy flushing issues, but it works now.

using (var sw = new StringWriter())
using (var csvWriter = new CsvWriter(sw, config))
{
    csvWriter.WriteRecords(records);
    return Encoding.UTF8.GetBytes(sw.ToString());
}
like image 794
WhiteleyJ Avatar asked Jun 01 '16 13:06

WhiteleyJ


1 Answers

Since CSVHelper is meant to collect several fields per row/line, it does some buffering itself until you tell it the current record is done:

csv.WriteField("test");
csv.NextRecord();
sr.Flush();

Now, the memstream should have the data in it. However, unless there is more processing elsewhere, the result in your OutputFile is wrong: Data will be byte[] not "text/csv". It seems like StringWriter would produce something more appropriate:

string sBuff;
using (StringWriter sw = new StringWriter())
using (CsvWriter csv = new CsvWriter(sw))
{
    csv.WriteRecord<SomeItem>(r);
    sBuff = sw.ToString();
}
Console.WriteLine(sBuff);

"New Item ",Falcon,7

like image 193
Ňɏssa Pøngjǣrdenlarp Avatar answered Sep 28 '22 03:09

Ňɏssa Pøngjǣrdenlarp