Export Datatable To Csv File Download In C# ((new)) Guide
: Ensure that cell values containing commas or quotes are properly escaped (e.g., wrapped in double quotes) to prevent breaking the CSV structure.
: Iterate through DataTable.Rows and join cell values with a delimiter (usually a comma). export datatable to csv file download in c#
: For large datasets, use a StreamWriter directly on the response output to minimize memory usage. Web API Example: : Ensure that cell values containing commas or
public static void ExportToCsv(DataTable dt, string filePath) { StringBuilder sb = new StringBuilder(); // Write Column Headers IEnumerable columnNames = dt.Columns.Cast ().Select(column => column.ColumnName); sb.AppendLine(string.Join(",", columnNames)); // Write Row Data foreach (DataRow row in dt.Rows) { IEnumerable fields = row.ItemArray.Select(field => string.Concat("\"", field.ToString().Replace("\"", "\"\""), "\"")); sb.AppendLine(string.Join(",", fields)); } File.WriteAllText(filePath, sb.ToString()); } Use code with caution. 2. Exporting for Web Download (ASP.NET / Web API) export datatable to csv file download in c#