Csharp--read Csv file to DataTable

Source: Internet
Author: User

The information found on the Internet is not so great, many code at a glance to know that there is no overall consideration.

finally found a good, on the CodePlex , the man wrote a framework, too heavy.

Http://www.codeproject.com/Articles/9258/A-Fast-CSV-Reader

It's really nice.

I didn't have the patience to see his implementation, and he tried to write the following code to complete the reading of CSV.

Reference : http://msdn.microsoft.com/en-us/library/ae5bf541%28v=vs.90%29.aspx

Only two methods were written, and the organization was not particularly elegant.

When you use it, you only need to call READCSV2DT, the incoming parameter is a Boolean value for the file path and whether the first row is the Header.

the second method is to replace Csvwri theextra double quotes in the TER package.

 Public StaticDataTable Readcsv2dt (stringFileNameBOOLIsfirstlineheader) {DataTable dt=NewDataTable ();intQuotecount =0;intLastbyte =0;intb =0;D Atarow Dr=NULL;BOOLIsfirstline =true;intColindex =0; List<string> firstlinefields =Newlist<string>(); StringBuilder SB=NewStringBuilder ();using(FileStream fs =file.openread (filename)) { while((b = fs.) ReadByte ())! =-1){if(!isfirstline && Dr = =NULL) Dr=dt. NewRow ();if(b = =Ten&& Lastbyte = = -&& Quotecount%2==0)//One Row finished{if(!isfirstline) {Dr[colindex]=sb. ToString ();d T. Rows.Add (DR);}Else{if(isfirstlineheader) dt. Columns.Add (sb.) ToString ());ElseFirstlinefields. ADD (sb.) ToString ());//Build the table Strucureif(Isfirstline &&!)Isfirstlineheader) { for(inti =1; I <= firstlinefields. Count; i++) {dt. Columns.Add ("Col"+i);} Dr=dt. NewRow (); for(intj =0; J < Firstlinefields. Count; J + +) {Dr[j]=firstlinefields[j];} Dt. Rows.Add (DR);} Isfirstline=false;} Sb. Clear (); Quotecount=0; b=0;d R=NULL; Colindex=0; Lastbyte=0;}Else if(b = = -&& Quotecount%2==0)//One filed found stand for comma{if(isfirstline) {if(isfirstlineheader) dt. Columns.Add (Removetextqualifier (sb.) ToString ()));ElseFirstlinefields. ADD (Removetextqualifier (sb.) ToString ()));}ElseDr[colindex] =removetextqualifier (sb.) ToString ()); sb. Clear (); Colindex++;}Else{if(b = = the) quotecount++;//"Lastbyte=B;SB. Append (UnicodeEncoding.ASCII.GetString (New byte[] {byte. Parse (B.tostring ())}); }};returnDT;}  Public Static stringRemovetextqualifier (stringtext) {stringPattern ="^\ "(? <word>[\\s\\s]*) \" $"; Regex RGX=NewRegex (Pattern,regexoptions.multiline); Match m=RGX. Match (text);if(m.success)//return M.result ("($)"). Replace ("\" \ "", "\" ");returnm.groups["Word"]. Value.replace ("\"\"","\"");ElsereturnText. Replace ("\"\"","\"");}

: Test a file, the effect can also, and Excel opens with no differences displayed.

If you need to test, make sure you write the file is a valid csv file, otherwise please use Excel Save As, write your own file suffix is not true csv.

Csharp--read Csv file to DataTable

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.