Skip to content

Mike Simmons

My Workbench

  • Home
  • LinkedIn
  • Home
  • Programming
  • C# save DataTable to CSV easily

C# save DataTable to CSV easily

Posted on March 16, 2018March 16, 2018 By Mike No Comments on C# save DataTable to CSV easily
C#, Programming

I find I need to save C# DataTables to CSV files often and as such use the following code:


public static void SaveToCsv(this DataTable data, string fileName)
{
using (var messageSave = new StreamWriter(fileName))
{
foreach (DataColumn col in data.Columns)
{
if (col.ColumnName.Contains("\""))
messageSave.Write($"\"{col.ColumnName}\",");
else
messageSave.Write($"{col.ColumnName},");
}
messageSave.Write(Environment.NewLine);
foreach (DataRow row in data.Rows)
{
foreach (object s in row.ItemArray)
{
if (s.ToString().Contains("\""))
messageSave.Write($"\"{s.ToString()}\",");
else
messageSave.Write($"{s.ToString()},");
}
messageSave.Write(Environment.NewLine);
}
}
}

Tags: C# CSV DataTable PROGRAMMING

Post navigation

❮ Previous Post: Easily save and load C# classes using XML Serialization
Next Post: Powershell script to create user home directory and DFS namespace target ❯

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

I accept that my given data and my IP address is sent to a server in the USA only for the purpose of spam prevention through the Akismet program.More information on Akismet and GDPR.

Pages

  • LinkedIn

Recent Posts

  • PowerShell Anti-Idle Script
  • WSUS MMC Crash Due To XML Invalid Character!
  • Open Maintenance – Docker & CentOS 7
  • Powershell script to create user home directory and DFS namespace target
  • C# save DataTable to CSV easily

Recent Comments

    Archives

    • August 2022
    • March 2018
    • July 2017
    • August 2015

    Categories

    • Active Directory
    • C#
    • CentOS
    • Docker
    • GrayLog
    • MSSQL
    • Networking
    • PowerShell
    • Programming
    • Uncategorized
    • Windows
    • XML

    Meta

    • Log in
    • Entries feed
    • Comments feed
    • WordPress.org

    Copyright © 2023 Mike Simmons.

    Theme: Oceanly by ScriptsTown