0

I'm trying to use the LinqToCsv NuGet package to output a CSV file to the browser. Creating the CSV part was previously done using a StringBuilder class, however we are trying to swap this out as it was messy.

Here is the code:

public HttpResponse ExportMessagesAsCSVNew()
{
    var messages = _myService.GetMessages();       
    
    CsvContext cc = new CsvContext();            

    MemoryStream memoryStream = new MemoryStream();
    TextWriter tw = new StreamWriter(memoryStream);

    cc.Write(messages, tw);

    var response = System.Web.HttpContext.Current.Response;

    response.BufferOutput = true;
    response.Clear();
    response.ClearHeaders();
    response.ContentEncoding = Encoding.Unicode;
    response.AddHeader("content-disposition", "attachment; filename=Messages.csv ");
    response.ContentType = "text/csv";
    response.Write(tw);
    response.End();

    return response;
}

When I open the CSV from the browser, I just get the string System.IO.StreamWriter outputted.

Question

How can I successfully create a CSV in the memory stream using LinqToCsv and then output it to the browser using the http response without having to physically create the file and store it on a drive somewhere?

JsonStatham
  • 9,770
  • 27
  • 100
  • 181
  • What type of app is this? Web Forms? MVC? Web API? .NET Framework? .NET Core? – mason Dec 12 '22 at 15:03
  • Sorry, its an MVC application using .Net Framework version 4.7.2 – JsonStatham Dec 12 '22 at 15:06
  • Okay, so with MVC, we don't directly write to the response. Instead, we return a FileResult from an action method. Is ExportMessagesAsCSVNew an action method? If so, there should be some helper methods available if you type `return File(` then Intellisense (assuming you're Visual Studio) should show you some overloads. – mason Dec 12 '22 at 15:14
  • I am not sure if it is the same in .NET6 like MVC but there you can do something like: byte[] fileBytes = System.IO.File.ReadAllBytes(YourFile); And after this, you can do: return File(fileBytes, "application/force-download", "YourFileName.csv"); – Lukas Hieronimus Adler Dec 12 '22 at 15:15
  • @mason Your advice was what I needed, put this into an answer and ill mark as correct, basically this worked: csvContext.Write(messageLogExportViewModelList, streamWriter); streamWriter.Flush(); return File(memoryStream.GetBuffer(), "text/csv"); – JsonStatham Dec 12 '22 at 15:23

0 Answers0