C # CSV file read and write

Source: Internet
Author: User

public class Csvfilehelper
{
<summary>
Writing data from a DataTable to a CSV file
</summary>
<param name= "DT" > provides datatable</param> to save data
<param name= file path for "FileName" >csv </param>
public static void Savecsv (DataTable dt, string fullPath)
{
FileInfo fi = new FileInfo (FullPath);
if (!fi. directory.exists)
{
Fi. Directory.create ();
}
FileStream fs = new FileStream (FullPath, System.IO.FileMode.Create, System.IO.FileAccess.Write);
StreamWriter SW = new StreamWriter (FS, System.Text.Encoding.Default);
StreamWriter SW = new StreamWriter (FS, System.Text.Encoding.UTF8);
String data = "";
Write out the column name
for (int i = 0; i < dt. Columns.count; i++)
{
Data + = dt. Columns[i]. Columnname.tostring ();
if (i < dt. COLUMNS.COUNT-1)
{
Data + = ",";
}
}
Sw. WriteLine (data);
Write each row of data
for (int i = 0; i < dt. Rows.Count; i++)
{
data = "";
for (int j = 0; j < dt. Columns.count; J + +)
{
String str = dt. ROWS[I][J]. ToString ();
str = str. Replace ("\" "," \ "\" ");//replacing the colon in English with a colon that requires two colons
if (str. Contains (', ') | | Str. Contains (' "')
|| Str. Contains (' \ r ') | | Str. Contains (' \ n '))//The need to enclose a comma with a colon line break in quotation marks
{
str = string. Format ("\" {0}\ "", str);
}

Data + = str;
if (J < dt. COLUMNS.COUNT-1)
{
Data + = ",";
}
}
Sw. WriteLine (data);
}
Sw. Close ();
Fs. Close ();
DialogResult result = MessageBox.Show ("CSV file saved successfully! ");
if (result = = DialogResult.OK)
{
System.Diagnostics.Process.Start ("Explorer.exe", Common.path_lang);
}
}

<summary>
Reading data from a CSV file into a DataTable
</summary>
<param name= "fileName" >csv file path </param>
<returns> returns the datatable</returns> that read the CSV data
public static DataTable Opencsv (String filePath)
{
Encoding Encoding = Common.gettype (FilePath); encoding.ascii;//
DataTable dt = new DataTable ();
FileStream fs = new FileStream (FilePath, System.IO.FileMode.Open, System.IO.FileAccess.Read);

StreamReader sr = new StreamReader (FS, Encoding.UTF8);
StreamReader sr = new StreamReader (fs, encoding);
String filecontent = Sr. ReadToEnd ();
encoding = Sr. currentencoding;
Record a row of records per read
String strLine = "";
Record the contents of each field in each row of records
string[] Aryline = null;
string[] Tablehead = null;
Number of marked columns
int columnCount = 0;
Indicates if the first line is read
bool IsFirst = true;
Read data in CSV row by line
while (StrLine = Sr. ReadLine ()) = null)
{
StrLine = Common.convertstringutf8 (strLine, encoding);
StrLine = Common.convertstringutf8 (strLine);

if (IsFirst = = True)
{
Tablehead = Strline.split (', ');
IsFirst = false;
ColumnCount = Tablehead.length;
Create columns
for (int i = 0; i < ColumnCount; i++)
{
DataColumn dc = new DataColumn (Tablehead[i]);
Dt. Columns.Add (DC);
}
}
Else
{
Aryline = Strline.split (', ');
DataRow dr = dt. NewRow ();
for (int j = 0; J < ColumnCount; J + +)
{
DR[J] = Aryline[j];
}
Dt. Rows.Add (DR);
}
}
if (aryline! = null && aryline.length > 0)
{
Dt. Defaultview.sort = Tablehead[0] + "+" ASC ";
}

Sr. Close ();
Fs. Close ();
return DT;
}
}

C # CSV file read and write

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.