shigarr
shigarr

Reputation: 72

LinqToCsv - not all the rows are written to the file

I am using LinqToCsv to write data to a CSV file. I have a list of objects that has 8 number of records, however, when I write the csv to the MemoryStream and then to the disk it writes only 7 of them. The code is as follows

var csvClaims = GetCSVClaims(webUser, searchString, isReferenceSearch);
CsvContext cc = new CsvContext();
CsvFileDescription outputFileDesc = new CsvFileDescription
{
   SeparatorChar = ',',
   FirstLineHasColumnNames = true
};
MemoryStream memStream = new MemoryStream();
TextWriter tw = new StreamWriter(memStream);
cc.Write(csvClaims, tw, outputFileDesc);
return memStream.ToArray();

I am not sure what am I missing. Any help would be greatly appreciated. I am not adding the CSVClaims class here as it is quite big but can be added if required.

Upvotes: 0

Views: 487

Answers (1)

Enigmativity
Enigmativity

Reputation: 117084

Try this:

var csvClaims = GetCSVClaims(webUser, searchString, isReferenceSearch);
CsvContext cc = new CsvContext();
CsvFileDescription outputFileDesc = new CsvFileDescription
{
    SeparatorChar = ',',
    FirstLineHasColumnNames = true
};
using (var memStream = new MemoryStream())
{
    using (var tw = new StreamWriter(memStream))
    {
        cc.Write(csvClaims, tw, outputFileDesc);
        tw.Flush();
        return memStream.ToArray();
    }
}

You need to flush the writer and dispose of your disposables.

Upvotes: 3

Related Questions