Transferred from: http://www.cnblogs.com/Clin/archive/2013/03/14/2959022.html
1 Public classCsvfilehelper2 {3 /// <summary>4 ///writing data from a DataTable to a CSV file5 /// </summary>6 /// <param name= "DT" >provide a DataTable for saving data</param>7 /// <param name= "FileName" >file path for CSV</param>8 Public Static voidSavecsv (DataTable DT,stringFullPath)9 {TenFileInfo fi =NewFileInfo (fullPath); One if(!fi. directory.exists) A { - fi. Directory.create (); - } theFileStream fs =NewFileStream (FullPath, System.IO.FileMode.Create, System.IO.FileAccess.Write); - //StreamWriter sw = new StreamWriter (FS, System.Text.Encoding.Default); -StreamWriter SW =NewStreamWriter (FS, System.Text.Encoding.UTF8); - stringdata =""; + //write out the column name - for(inti =0; i < dt. Columns.count; i++) + { AData + =dt. Columns[i]. Columnname.tostring (); at if(I < dt. Columns.count-1) - { -Data + =","; - } - } - SW. WriteLine (data); in //write each row of data - for(inti =0; i < dt. Rows.Count; i++) to { +data =""; - for(intj =0; J < dt. Columns.count; J + +) the { * stringstr =dt. ROWS[I][J]. ToString (); $str = str. Replace ("\"","\"\"");//Replace the colon with the English colon to be replaced by two colonsPanax Notoginseng if(str. Contains (',') || Str. Contains ('"') -|| Str. Contains ('\ r') || Str. Contains ('\ n'))//need to enclose the comma with a colon line break in quotation marks the { +str =string. Format ("\ "{0}\"", str); A } the +Data + =str; - if(J < dt. Columns.count-1) $ { $Data + =","; - } - } the SW. WriteLine (data); - }Wuyi SW. Close (); the FS. Close (); -DialogResult result = MessageBox.Show ("CSV file saved successfully! "); Wu if(Result = =DialogResult.OK) - { AboutSystem.Diagnostics.Process.Start ("Explorer.exe", Common.path_lang); $ } - } - - /// <summary> A ///reading data from a CSV file into a DataTable + /// </summary> the /// <param name= "FileName" >csv file path</param> - /// <returns>returns a DataTable that reads CSV data</returns> $ Public StaticDataTable Opencsv (stringFilePath) the { theEncoding Encoding = Common.gettype (FilePath);//Encoding.ascii;// theDataTable dt =NewDataTable (); theFileStream fs =NewFileStream (FilePath, System.IO.FileMode.Open, System.IO.FileAccess.Read); - in //StreamReader sr = new StreamReader (FS, Encoding.UTF8); theStreamReader sr =NewStreamReader (fs, encoding); the //string filecontent = Sr. ReadToEnd (); About //encoding = Sr. currentencoding; the //record a row of records per read the stringStrLine =""; the //record the contents of each field in each row of records + string[] Aryline =NULL; - string[] Tablehead =NULL; the //number of marked columnsBayi intColumnCount =0; the //indicates if the first line is read the BOOLIsFirst =true; - //read data in CSV row by line - while((StrLine = Sr.) ReadLine ())! =NULL) the { the //strLine = Common.convertstringutf8 (strLine, encoding); the //strLine = Common.convertstringutf8 (strLine); the - if(IsFirst = =true) the { theTablehead = Strline.split (','); theIsFirst =false;94ColumnCount =tablehead.length; the //Create Columns the for(inti =0; i < ColumnCount; i++) the {98DataColumn DC =NewDataColumn (Tablehead[i]); About dt. Columns.Add (DC); - }101 }102 Else103 {104Aryline = Strline.split (','); theDataRow dr =dt. NewRow ();106 for(intj =0; J < ColumnCount; J + +)107 {108DR[J] =Aryline[j];109 } the dt. Rows.Add (DR);111 } the }113 if(Aryline! =NULL&& aryline.length >0) the { theDt. Defaultview.sort = tablehead[0] +" "+"ASC"; the }117 118 Sr. Close ();119 FS. Close (); - returnDT;121 }122}
CSV file read/write