Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Writing CSV to MemoryStream using LinqToCSV does not return any data

I've verified using System.Text.Encoding.ASCII.GetString(ms.ToArray)); that my memorystream has the expected data.

However using the LinqToCSV nuget library will not generate my csv file. I get no errors or exceptions thrown. I just get an empty file when I'm prompted to open the file.

Here is my Action Method

 public FileStreamResult  Export(){

        var results = _service.GetProperties().Take(3);
        System.IO.MemoryStream ms = new System.IO.MemoryStream();
        System.IO.TextWriter  txt = new System.IO.StreamWriter(ms); 


        CsvFileDescription inputFileDescription = new CsvFileDescription{
            SeparatorChar =',',
            FirstLineHasColumnNames = true
        }
            ; 

        CsvContext csv = new CsvContext();

        csv.Write(results,txt,inputFileDescription);



        return File(ms , "application/x-excel"); 
    }

I find it interesting, if I change the return type to contentResult, and the return method to Content() and pass it System.Text.Encoding.ASCII.GetString(ms.ToArray)); I do get a browser window showing my data.

like image 328
Doug Chamberlain Avatar asked Dec 27 '22 07:12

Doug Chamberlain


2 Answers

Make sure you reset stream position to 0. Also make sure you flush your StreamWriter before that.

like image 194
Ilia G Avatar answered May 01 '23 05:05

Ilia G


Calling the Web API method to return CVS file from JavaScript.

public HttpResponseMessage Bidreport([FromBody]int formData).....

Fill in your IEnumerable<YourObject>query = from LINQ query .... This is how to return it:

 using (var ms = new MemoryStream())
            {
                using (TextWriter txt = new StreamWriter(ms))
                {
                    var cc = new CsvContext();
                    cc.Write(query, txt, outputFileDescription);
                    txt.Flush();
                    ms.Position = 0;
                    var fileData = Encoding.ASCII.GetString(ms.ToArray());
                    var result = new HttpResponseMessage(HttpStatusCode.OK) {Content = new StringContent(fileData)};
                    result.Content.Headers.ContentType = new MediaTypeHeaderValue("application/x-excel");
                    return result;
                }
            }         
like image 28
odesuk Avatar answered May 01 '23 05:05

odesuk