C # CSV file read/write

Source: Internet
Author: User
Tags first row

CSV is a common, relatively simple file format, the most widely used is the transfer of tabular data between programs, and these programs themselves are in an incompatible format to operate. So how does C # Read and write to CSV format files? CSV data format does not have a very uniform standard but in order to avoid errors we developed a unified format like this:

"Name", "pwd", "date"

"John", "123", "2015-09-30"

And then the default format for code processing is this. why use a CSV file this involves the problem of data interoperability, some programs support the form of data other programs are not necessarily supported, and CSV format is supported by most applications, So it's a good choice to save the data in exchange. Note: When the file is processed, be sure to close the release data stream otherwise the file will be occupied CSV does not have strict standards, many people must develop a good format, unified development One, DataTable data to write CSV file

public static void Savecsv (DataTable dt, string fullpath)//table data writes to CSV {System.IO.FileInfo fi = new System.IO.FileIn
    Fo (fullpath); if (!fi. directory.exists) {fi.
    Directory.create (); System.IO.FileStream fs = new System.IO.FileStream (FullPath, System.IO.FileMode.Create, System.IO.FileAcces
    S.write);
    System.IO.StreamWriter SW = new System.IO.StreamWriter (FS, System.Text.Encoding.UTF8);

    String data = ""; for (int i = 0; i < dt. Columns.count; i++)//write column name {data + + dt. Columns[i].
        Columnname.tostring (); if (i < dt.
        COLUMNS.COUNT-1) {Data + = ","; } SW.

    WriteLine (data); for (int i = 0; i < dt. Rows.Count;
        i++)//writes each row data {""; for (int j = 0; j < dt.) Columns.count; J + +) {string str = dt. ROWS[I][J].
            ToString (); str = str. Replace ("\" "," \ "\");//replacing the English colon English colon requires two colon if (str). Contains (', ') | | Str. Contains (' "")
                || Str. Contains (' \ r ') | | Str. Contains (' \ n '))///The need to enclose a comma colon line break is enclosed in quotation marks {str = string.
            Format ("\" {0}\ "", str);
            } data + + str; if (J < dt.
            COLUMNS.COUNT-1) {Data + = ","; } SW.
    WriteLine (data); } SW.
    Close (); Fs.
Close (); }
Two, reading CSV files to DataTable
public static DataTable Opencsv (string filePath)//Read data from CSV return table {System.Text.Encoding Encoding = GetType (FilePath);
    encoding.ascii;//DataTable dt = new DataTable (); 

    System.IO.FileStream fs = new System.IO.FileStream (FilePath, System.IO.FileMode.Open, System.IO.FileAccess.Read);

    System.IO.StreamReader sr = new System.IO.StreamReader (fs, encoding);
    Record string strLine = "" for each read line;
    Record the contents of each field in each row string[] aryline = null;
    string[] Tablehead = null;
    Number of marked columns int columnCount = 0;
    Indicates whether the first row is read bool Isfirst = true; Read data in CSV line-by-row while (StrLine = Sr.
            ReadLine ())!= null) {if (Isfirst = = true) {Tablehead = Strline.split (', ');
            Isfirst = false;
            ColumnCount = Tablehead.length; Create column for (int i = 0; i < ColumnCount i++) {DataColumn dc = new DataColumn (ta
                Blehead[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; ///the path of a given file, reads the binary data of the file, determines the encoding type of the file///<param name= "file_name" > File path </param>///<returns> file encoding type </returns> public static System.Text.Encoding GetType (string file_name) {System.IO.FileStream fs = new System. Io.
    FileStream (file_name, System.IO.FileMode.Open, System.IO.FileAccess.Read);
    System.Text.Encoding r = GetType (FS); Fs.
    Close ();
return R;
///to determine the encoding type of the file through a given file stream///<param name= "FS" > File flow </param>///<returns> file encoding type </returns> public static System.Text.EncodinG GetType (System.IO.FileStream fs) {byte[] Unicode = new byte[] {0xFF, 0xFE, 0x41};
    byte[] Unicodebig = new byte[] {0xFE, 0xFF, 0x00}; byte[] UTF8 = new byte[] {0xEF, 0xBB, 0xBF};

    With BOM System.Text.Encoding reVal = System.Text.Encoding.Default;
    System.IO.BinaryReader r = new System.IO.BinaryReader (FS, System.Text.Encoding.Default);
    int i; Int. TryParse (fs.
    Length.tostring (), out i);
    byte[] ss = R.readbytes (i); if (isutf8bytes (ss) | |
    (Ss[0] = 0xEF && ss[1] = = 0xBB && ss[2] = 0xBF)
    {reVal = System.Text.Encoding.UTF8; else if (ss[0] = = 0xFE && ss[1] = = 0xFF && ss[2] = = 0x00) {ReVal = System.Text.Encoding .
    Bigendianunicode; else if (ss[0] = = 0xFF && ss[1] = = 0xFE && ss[2] = = 0x41) {ReVal = System.Text.Encoding .
    Unicode;
    } r.close ();
return reVal; ///determine if the UTF8 format is not BOM///<param name= "Data" ></param>///<returns></returns> private static bool Isutf8bytes (byte[] Data {int charbytecounter = 1; Calculates the number of bytes that are currently being parsed Fu Ching byte Curbyte;
    The byte of the current analysis. for (int i = 0; i < data. Length;
        i++) {curbyte = Data[i];
                if (Charbytecounter = = 1) {if (Curbyte >= 0x80) {//judge the current
                while ((Curbyte <<= 1) & 0x80)!= 0) {charbytecounter++; }//Mark bit first if not 0 then at least 2 1 start as: 110XXXXX ...  1111110X if (charbytecounter = 1 | | charbytecounter > 6) {return
                False }} else {//if UTF-8 at this time the first digit must be 1 if ((Curbyte & 0xc0)!= 0
            X80) {return false;
        } charbytecounter--; } if (Charbytecounter > 1) {throw new Exception ("Not expected byte format");
return true; }
Third, modify the name of the fileWe need to save historical data or know that the file is modified in real time by changing the name of the file, plus the date of the day, and so on.
public static bool Changefilename (string OldPath, String NewPath) 
{
    bool re = false;
    Try 
    {
        if (file.exists (OldPath)) 
        {
            file.move (OldPath, NewPath);
            Re = true;
        }
    }
    Catch 
    {
        re = false;
    }
    return re;
}
data writing for CSV files
Directly write files in a CSV file by submitting data in a Web page form
public static bool Savecsv (string fullpath,string Data) {bool re = true;
        try {FileStream FileStream = new FileStream (FullPath, filemode.append);
        StreamWriter sw = new StreamWriter (FileStream, System.Text.Encoding.UTF8); Sw.
        WriteLine (Data); Empty the buffer sw.
        Flush (); Close the stream SW.
        Close ();
    Filestream.close ();
    catch {re = false;
return to re; }
Related Article

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.