If your application requires advanced features like Excel-to-CSV conversion or complex formatting, libraries like or EasyXLS offer one-line methods to save DataTables directly.
This method is highly efficient for most console applications because it provides full control over delimiters and character escaping. Create the Header Row IEnumerable columnNames = dt
using System; using System.Data; using System.IO; using System.Linq; using System.Text; public static void ExportToCsv(DataTable dt, string filePath) { StringBuilder sb = new StringBuilder(); // 1. Create the Header Row IEnumerable columnNames = dt.Columns.Cast (). Select(column => column.ColumnName); sb.AppendLine(string.Join(",", columnNames)); // 2. Add Data Rows foreach (DataRow row in dt.Rows) { IEnumerable fields = row.ItemArray.Select(field => string.Concat("\"", field.ToString().Replace("\"", "\"\""), "\"")); sb.AppendLine(string.Join(",", fields)); } // 3. Save to File File.WriteAllText(filePath, sb.ToString(), Encoding.UTF8); } Use code with caution. Best Practices for Console Applications Save to File File
: Always wrap fields in double quotes and escape existing quotes by doubling them ( "" ) to prevent breaking the CSV structure if your data contains commas or newlines. Save to File File.WriteAllText(filePath