SoFunction
Updated on 2025-03-07

C# operation CSV file class example

This article describes the C# operation of CSV file classes. Share it for your reference. The specific analysis is as follows:

This C# class is used to convert DataTable to CSV files and CSV files into DataTable. If you need to convert between CSV and DataTable, this class is very suitable.

using ;
using ;
namespace 
{
 /// <summary>
 /// CSV file conversion class /// </summary>
 public static class CsvHelper
 {
  /// <summary>
  /// Export the report as Csv  /// </summary>
  /// <param name="dt">DataTable</param>
  /// <param name="strFilePath">Physical Path</param>  /// <param name="tableheader">Tableheader</param>  /// <param name="columname">field title, comma-separated</param>  public static bool dt2csv(DataTable dt, string strFilePath, string tableheader, string columname)
  {
   try
   {
    string strBufferLine = "";
    StreamWriter strmWriterObj = new StreamWriter(strFilePath, false, .UTF8);
    (tableheader);
    (columname);
    for (int i = 0; i &lt; ; i++)
    {
     strBufferLine = "";
     for (int j = 0; j &lt; ; j++)
     {
      if (j &gt; 0)
       strBufferLine += ",";
      strBufferLine += [i][j].ToString();
     }
     (strBufferLine);
    }
    ();
    return true;
   }
   catch
   {
    return false;
   }
  }
  /// &lt;summary&gt;
  /// Read Csv into DataTable  /// &lt;/summary&gt;
  /// <param name="filePath">csv file path</param>  /// <param name="n"> means that line n is the field title, line n+1 is the record start</param>  public static DataTable csv2dt(string filePath, int n, DataTable dt)
  {
   StreamReader reader = new StreamReader(filePath, .UTF8, false);
   int i = 0, m = 0;
   ();
   while (() &gt; 0)
   {
    m = m + 1;
    string str = ();
    if (m &gt;= n + 1)
    {
     string[] split = (',');
      dr = ();
     for (i = 0; i &lt; ; i++)
     {
      dr[i] = split[i];
     }
     (dr);
    }
   }
   return dt;
  }
 }
}

I hope this article will be helpful to everyone's C# programming.