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?
