C # How to read CSV files

Source: Internet
Author: User

In many systems, you need to read CSV files. I have encountered in a previous project that reads data from the CSV file to the datatable for processing.Code

The method I previously wrote to import the data in the CSV file to the able. Now I will post it to share with you:

// Getcsvfile's filename and data get the data in the CSV file and import the data into the able

// Mycsvdt is used to hold the data datatable In the CSV file. filepath refers to the path of the CSV file.

Private bool opencsvfile (ref datatable mycsvdt, string filepath)
{
String strpath = filepath; // path of the CSV file
Try
{
Int intcolcount = 0;
Bool blnflag = true;

Datacolumn mydc;
Datarow mydr;

String strline;
String [] aryline;
Streamreader mysr = new streamreader (strpath, system. Text. encoding. Default );

While (strline = mysr. Readline ())! = NULL)
{
Aryline = strline. Split (New char [] {','});

// Add the column name to the datatable
If (blnflag)
{
Blnflag = false;
Intcolcount = aryline. length;
Int Col = 0;
For (INT I = 0; I <aryline. length; I ++)
{
Col = I + 1;
Mydc = new datacolumn (Col. tostring ());
Mycsvdt. Columns. Add (mydc );
}
}

// Fill in the data and add it to the able
Mydr = mycsvdt. newrow ();
For (INT I = 0; I <intcolcount; I ++)
{
Mydr [I] = aryline [I];
}
Mycsvdt. Rows. Add (mydr );
}
Return true;

}< br> catch (exception e)
{< br>
throw (stack. geterrorstack (strpath + "error in reading CSV file data. "+ E. message, "opencsvfile (");
return false;
}< BR >}

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.