Convert A Generic List To CSV File In C#

This is an example of how to convert a generic list to a dynamic downloadable .csv file using C#, the CsvHelper library and the FileStreamResult.

Download the repo and run the full project solution from Github

In this example a request comes into the controller, we create a generic list of type ListItem, created a memory stream and using the CsvWriter library  return a dynamic .csv file to the browser.

Step 1: Create the generic list class
This class will hold our generic list items. This can be whatever data you need.

public class ListItem
{
    public int Id { get; set; }
    public string Name { get; set; }
}

Step 2: Create the MVC action to return the CSV file
This action method creates the generic list, writes it to memory with help from the CsvHelper library and returns the FileStreamResult back to the browser.

//Action Method for your controller
[HttpPost]
public ActionResult ConvertToCSV()
{
    //Create the test list
    var list = new List<ListItem>()
    {
        new ListItem(){Id = 1, Name = "Jerry"},
        new ListItem(){Id = 2, Name="George"},
        new ListItem(){Id = 3, Name="Kramer"},
        new ListItem(){Id = 4, Name = "Elaine"}
     };

    byte[] result;
    using (var memoryStream = new MemoryStream())
    {
        using (var streamWriter = new StreamWriter(memoryStream))
        {
            using (var csvWriter = new CsvWriter(streamWriter))
            {
                csvWriter.WriteRecords(list);
                streamWriter.Flush();
                result = memoryStream.ToArray();
            }
         }
     }

     return new FileStreamResult(new MemoryStream(result), "text/csv") { FileDownloadName = "filename.csv" };
}

h/t to this StackOverflow post

Download the repo and run the full project solution from Github