C# Export Csv Download |verified| May 2026
using CsvHelper; using System.Globalization; public IActionResult ExportWithCsvHelper() { var records = _dbContext.Users.ToList(); using var memoryStream = new MemoryStream(); using (var writer = new StreamWriter(memoryStream)) using (var csv = new CsvWriter(writer, CultureInfo.InvariantCulture)) { csv.WriteRecords(records); } return File(memoryStream.ToArray(), "text/csv", "ExportedData.csv"); } Use code with caution. 3. Handling Large Datasets (Streaming)
Using a MemoryStream ensures the file is generated in memory before being sent to the client. c# export csv download
Providing a third argument to the File() method triggers the "Save As" dialog with a predefined name. using CsvHelper; using System
Exporting data to a CSV file and triggering a browser download is a foundational requirement for many C# web applications. Whether you are building an site or a Web API , the process generally involves converting a collection of objects into a formatted string or stream and returning it with the correct MIME type. 1. The Quickest Method: Manual Formatting Providing a third argument to the File() method
public IActionResult DownloadCsv() { var data = new List { new { Id = 1, Name = "Alice", Email = "alice@example.com" }, new { Id = 2, Name = "Bob", Email = "bob@example.com" } }; var builder = new StringBuilder(); builder.AppendLine("Id,Name,Email"); // Header foreach (var item in data) { builder.AppendLine($"{item.Id},{item.Name},{item.Email}"); } return File(Encoding.UTF8.GetBytes(builder.ToString()), "text/csv", "users.csv"); } Use code with caution. 2. The Professional Standard: CsvHelper
If you need features beyond simple exports, such as Excel-to-CSV conversion or advanced styling, consider these libraries:
c# - Returning CSV from .NET Core controller - Stack Overflow