CSVHelper - no way out

I am trying to create a csv file using CSVHelpernuGet package

This is the code

public ActionResult Test()
{
    var ms = new MemoryStream();
    var sr = new StreamWriter(ms);
    var csv = new CsvWriter(sr);

    csv.WriteField("sd");
    csv.WriteField("sd");
    csv.WriteField("sd");
    csv.WriteField("sd");

    //ms.Seek(0, 0);
    sr.Flush();
    //ms.Position = 0;
    var len = ms.Length;

    return File(ms, "text/csv", "test.csv");
}

However, the file is always empty.

I read here a few questions that suggest what StreamWriterneeds to be cleared. The position has moved to 0. However, Ive tried this and it doesn't seem to work

I also tried the same with the operators usingfor MemoryStream, StreamWriterand CSVWriter I tried all this and it is still empty.

Moreover, the length is MemoryStreamalways zero

What am I doing wrong?

+4
source share
3 answers

Found out that I need to pass an array of bytes instead of a stream to FileContentResult:

return File(ms.ToArray(), "text/csv", "test.csv");
+1
source

, , WriteField writer.NextRecord(); csv :

using (var sw = new StreamWriter(@"test.csv"))
        {
            var writer = new CsvWriter(sw);
            writer.WriteField("Fist field");
            writer.NextRecord();
            writer.WriteField("Second field");
            writer.NextRecord();
            //add what you wana here
        }
0

CsvHelper , , sw.Flush()

Using CsvWriter without configuration works fine

CsvWriter(sw); // with no configuration

Using configuration IgnoreReferences = true, I came up with an empty csv

CsvWriter(sw, new Configuration.CsvConfiguration() {
    Delimiter = ";", 
    IgnoreReferences = true
});

Solution (full example)

var ms = new System.IO.MemoryStream();
var sw = new System.IO.StreamWriter(ms);
var csvOut = new CsvWriter(sw, new Configuration.CsvConfiguration() { Delimiter = ";", IgnoreReferences = true });

csvOut.WriteRecords(someCollection);

// IMPORTANT LINE
sw.Flush();

ms.Position = 0;
return File(ms, "text/csv", "resultFile.csv");

Hint found on Github: https://github.com/JoshClose/CsvHelper/issues/47

0
source

Source: https://habr.com/ru/post/1546336/


All Articles