C # CSV file read and write

Source: Internet
Author: User

CSV file is very interesting, you can check online, notepad format files and CSV can be converted to each other, so do not use CSV as Excel file processing, but ordinary files can be

 Public classcsvfilehelper{/// <summary>    ///writing data from a DataTable to a CSV file/// </summary>    /// <param name= "DT" >provide a DataTable for saving data</param>    /// <param name= "FileName" >file path for CSV</param>     Public Static voidSavecsv (DataTable DT,stringFullPath) {FileInfo fi=NewFileInfo (FullPath); if(!fi. directory.exists) {fi.        Directory.create (); } FileStream 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++) {Data+=dt. Columns[i].            Columnname.tostring (); if(I < dt. Columns.count-1) {Data+=","; }} SW.        WriteLine (data); //write each row of data         for(inti =0; i < dt. Rows.Count; i++) {Data="";  for(intj =0; J < dt. Columns.count; J + +)            {                stringstr =dt. ROWS[I][J].                ToString (); STR= str. Replace ("\"","\"\"");//Replace the colon with the English colon to be replaced by two colons                if(str. Contains (',') || Str. Contains ('"')                     || Str. Contains ('\ r') || Str. Contains ('\ n'))//need to enclose the 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 a DataTable that reads CSV data</returns>     Public StaticDataTable Opencsv (stringFilePath) {Encoding Encoding= Common.gettype (FilePath);//Encoding.ascii;//DataTable dt =NewDataTable (); FileStream FS=NewFileStream (FilePath, System.IO.FileMode.Open, System.IO.FileAccess.Read); //StreamReader sr = new StreamReader (FS, Encoding.UTF8);StreamReader sr =NewStreamReader (fs, encoding); //string filecontent = Sr.        ReadToEnd (); //encoding = Sr.        currentencoding; //record a row of records per read        stringStrLine =""; //record the contents of each field in each row of records        string[] Aryline =NULL; string[] Tablehead =NULL; //number of marked columns        intColumnCount =0; //indicates if the first line is read        BOOLIsFirst =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(inti =0; i < ColumnCount; i++) {DataColumn DC=NewDataColumn (Tablehead[i]); Dt.                Columns.Add (DC); }            }            Else{aryline= Strline.split (','); DataRow Dr=dt.                NewRow ();  for(intj =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 (); returnDT; }}

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.