Writing CSV to MemoryStream using LinqToCSV does not return any data

本秂侑毒 提交于 2019-12-12 13:25:51

问题


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.


回答1:


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




回答2:


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;
                }
            }         


来源:https://stackoverflow.com/questions/15436354/writing-csv-to-memorystream-using-linqtocsv-does-not-return-any-data

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!