SoFunction
Updated on 2025-03-01

c# Operation on CSV file (write, read, modify)

1. DataTable data is written to CSV file

public static void SaveCSV(DataTable dt, string fullPath)//Table data is written to csv{
   fi = new (fullPath);
  if (!)
  {
    ();
  }
   fs = new (fullPath, , 
    );
   sw = new (fs, .UTF8);
  string data = "";
 
  for (int i = 0; i < ; i++)//Write column name  {
    data += [i].();
    if (i <  - 1)
    {
      data += ",";
    }
  }
  (data);
 
  for (int i = 0; i < ; i++) //Write data in each row  {
    data = "";
    for (int j = 0; j < ; j++)
    {
      string str = [i][j].ToString();
      str = ("\"", "\"\"");//Replace the English colon. The English colon needs to be replaced with two colons.      if ((',') || ('"')
        || ('\r') || ('\n')) //Including commas, colon, line breaks, need to be put into quotes      {
        str = ("\"{0}\"", str);
      }
 
      data += str;
      if (j <  - 1)
      {
        data += ",";
      }
    }
    (data);
  }
  ();
  ();
}

2. Read CSV file to DataTable

public static DataTable OpenCSV(string filePath)//Return table after reading data from csv{
   encoding = GetType(filePath); //;//
  DataTable dt = new DataTable();
   fs = new (filePath, , 
    );
 
   sr = new (fs, encoding);
 
  //Record one row of records read each time  string strLine = "";
  //Record the content of each field in each row of records  string[] aryLine = null;
  string[] tableHead = null;
  //Display the number of columns  int columnCount = 0;
  //Sign whether it is the first line of read  bool IsFirst = true;
  //Read data in CSV line by line  while ((strLine = ()) != null)
  {
    if (IsFirst == true)
    {
      tableHead = (',');
      IsFirst = false;
      columnCount = ;
      //Create a column      for (int i = 0; i < columnCount; i++)
      {
        DataColumn dc = new DataColumn(tableHead[i]);
        (dc);
      }
    }
    else
    {
      aryLine = (',');
      DataRow dr = ();
      for (int j = 0; j < columnCount; j++)
      {
        dr[j] = aryLine[j];
      }
      (dr);
    }
  }
  if (aryLine != null &&  > 0)
  {
     = tableHead[0] + " " + "asc";
  }
 
  ();
  ();
  return dt;
}
/// Given the path of the file, read the binary data of the file, and judge the encoding type of the file/// <param name="FILE_NAME">File path</param>/// <returns> File encoding type</returns> 
public static  GetType(string FILE_NAME)
{
   fs = new (FILE_NAME, , 
    );
   r = GetType(fs);
  ();
  return r;
}
 
/// Determine the encoding type of the file through the given file stream/// <param name="fs">File Stream</param>/// <returns> File encoding type</returns>public static  GetType( fs)
{
  byte[] Unicode = new byte[] { 0xFF, 0xFE, 0x41 };
  byte[] UnicodeBIG = new byte[] { 0xFE, 0xFF, 0x00 };
  byte[] UTF8 = new byte[] { 0xEF, 0xBB, 0xBF }; //With BOM   reVal = ;
 
   r = new (fs, );
  int i;
  ((), out i);
  byte[] ss = (i);
  if (IsUTF8Bytes(ss) || (ss[0] == 0xEF &amp;&amp; ss[1] == 0xBB &amp;&amp; ss[2] == 0xBF))
  {
    reVal = .UTF8;
  }
  else if (ss[0] == 0xFE &amp;&amp; ss[1] == 0xFF &amp;&amp; ss[2] == 0x00)
  {
    reVal = ;
  }
  else if (ss[0] == 0xFF &amp;&amp; ss[1] == 0xFE &amp;&amp; ss[2] == 0x41)
  {
    reVal = ;
  }
  ();
  return reVal;
}
 
/// Determine whether it is UTF8 format without BOM/// &lt;param name="data"&gt;&lt;/param&gt;
/// &lt;returns&gt;&lt;/returns&gt;
private static bool IsUTF8Bytes(byte[] data)
{
  int charByteCounter = 1;  // Calculate the number of bytes that should still exist in the character being analyzed.  byte curByte; //The bytes currently analyzed.  for (int i = 0; i &lt; ; i++)
  {
    curByte = data[i];
    if (charByteCounter == 1)
    {
      if (curByte &gt;= 0x80)
      {
        //Judge the current        while (((curByte &lt;&lt;= 1) &amp; 0x80) != 0)
        {
          charByteCounter++;
        }
        //If the first bit of the mark is not 0, it starts with at least 2 1s, such as: 110XXXXX............1111110X        if (charByteCounter == 1 || charByteCounter &gt; 6)
        {
          return false;
        }
      }
    }
    else
    {
      //If it is UTF-8, the first position must be 1      if ((curByte &amp; 0xC0) != 0x80)
      {
        return false;
      }
      charByteCounter--;
    }
  }
  if (charByteCounter &gt; 1)
  {
    throw new Exception("Unexpected byte format");
  }
  return true;
}

3. Modify the file name

We need to save historical data or know in real time which file is modified. You can change the name of the file such as adding the date of the day, etc.

public static bool ChangeFileName(string OldPath, string NewPath) 
{
  bool re = false;
  try 
  {
    if ((OldPath)) 
    {
      (OldPath, NewPath);
      re = true;
    }
  }
  catch 
  {
    re = false;
  }
  return re;
}

4. Data writing of CSV file

Submit data directly in web form and save it in csv file. Write it directly to the file

public static bool SaveCSV(string fullPath,string Data)
{
  bool re = true;
  try
  {
    FileStream FileStream = new FileStream(fullPath, );
    StreamWriter sw = new StreamWriter(FileStream, .UTF8);
    (Data);
    //Clear the buffer    ();
    //Close the flow    ();
    ();
  }
  catch 
  {
    re = false;
  }
  return re;
}

The above is the detailed content of c#'s operations on CSV file (write, read, and modify). For more information about C# csv files, please pay attention to my other related articles!