C # Perfect Read csv

Source: Internet
Author: User

C # Read and write CSV, in general, according to the separator (most commonly used comma delimiter) automatically segmentation

However, special cases, such as delimited statements in the table, require special parsing




Corresponding text content:






Using System;
Using System.Collections.Generic;
Using System.IO;

Using System.Text; namespace Readwritecsv {///<summary>///Class to store one CSV row///</summary> public cl
    Ass csvrow:list<string> {public string Linetext {get; set;} }///<summary>///class to write data to a CSV file///</summary> public class Csvfilewrit

        Er:streamwriter {public csvfilewriter (Stream stream): base (stream) {}
        Public Csvfilewriter (String filename): base (filename) {}///<summary>
        Writes a single row to a CSV file. </summary>///<param name= "Row" >the row to is written</param> public void Writerow (
            Csvrow row) {StringBuilder builder = new StringBuilder ();
            bool Firstcolumn = true;
         foreach (string value in row)   {//ADD separator If this isn ' t the ' the ' of the ' Builder.
                Append (', '); Implement special handling for values so contain comma or quote//enclose in quotes and double up Y double quotes if (value. IndexOfAny (new char[] {', ', '} ')!=-1) builder. AppendFormat ("\" {0}\ ""), value.
                Replace ("\" "," \ "\")); Else Builder.
                Append (value);
            Firstcolumn = false; } row. Linetext = Builder.
            ToString (); WriteLine (row.
        Linetext); }///<summary>///class to read data in CSV file///</summary> public class CSVF

        Ilereader:streamreader {public Csvfilereader (Stream stream): base (stream) {}

    Public Csvfilereader (String filename): base (filename) {}    <summary>///reads a row of data from a CSV file///</summary>///<param
        Name= "Row" ></param>///<returns></returns> public bool Readrow (Csvrow Row) {row.
            Linetext = ReadLine (); if (String.IsNullOrEmpty row.

            Linetext)) return false;
            int pos = 0;

            int rows = 0; while (Pos < row.

                Linetext.length) {string value; Special handling for quoted field if (row.

                    Linetext[pos] = = ' "') {//Skip initial quote pos++;
                    Parse quoted value int start = pos; while (Pos < row. Linetext.length) {//Test for quote character if (row .
         Linetext[pos] = = = ' "') {                   Found one pos++;
                            If two quotes together, keep one//otherwise, indicates end of if (POS >= row. Linetext.length | | Row.
                                Linetext[pos]!= ' "') {pos--;
                            Break
                    }} pos++; } value = row.
                    Linetext.substring (start, Pos-start); Value = value.
                Replace ("\" \ "", "\");
                    else {//Parse unquoted value int start = pos; while (Pos < row. Linetext.length && Row.
                    Linetext[pos]!= ', ') pos++; Value = row.
                Linetext.substring (start, Pos-start);

             }   Add field to list if rows < row.
                Count) Row[rows] = value; Else row.
                ADD (value);

                rows++; Eat up to and including the next comma while (Pos < row. Linetext.length && Row.
                Linetext[pos]!= ', ') pos++; if (Pos < row.
            Linetext.length) pos++; }//Delete any unused the items while row. Count > Rows) row.

            RemoveAt (rows); return TRUE if no columns read return (row.
        Count > 0); }
    }
}


Test method:


void Writetest ()
{
    //Write sample data to CSV file
    using (csvfilewriter writer = new Csvfilewriter ("Writetest . csv "))
    {for
        (int i = 0; i < i++)
        {
            Csvrow row = new Csvrow ();
            for (int j = 0; J < 5; j)
                Row. ADD (String.Format ("Column{0}", j));
            Writer. Writerow (row);

}} void Readtest ()
{
    //Read sample data from CSV file
    using (Csvfilereader reader = new Csvfilereader ("Readte St.csv "))
    {
        Csvrow row = new Csvrow ();
        while (reader. Readrow (Row))
        {
            foreach (string s in row)
            {
                Console.Write (s);
                Console.Write ("");
            }
            Console.WriteLine ();}}


Original link: http://www.codeproject.com/Articles/415732/Reading-and-Writing-CSV-Files-in-Csharp


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.