C # example of two methods for reading CSV files

Source: Internet
Author: User

Method 1: the plain text method reads the file as a text file.
Int intColCount = 0;
Bool blnFlag = true;
DataTable mydt = new DataTable ("myTableName ");

DataColumn mydc;
DataRow mydr;

String strpath = ""; // cvs file path
String strline;
String [] aryline;

System. IO. StreamReader mysr = new System. IO. StreamReader (strpath );

While (strline = mysr. ReadLine ())! = Null)
{
Aryline = strline. Split (new char [] {,});

If (blnFlag)
{
BlnFlag = false;
IntColCount = aryline. Length;
For (int I = 0; I <aryline. Length; I)
{
Mydc = new DataColumn (aryline [I]);
Mydt. Columns. Add (mydc );
}
}

Mydr = mydt. NewRow ();
For (int I = 0; I <intColCount; I)
{
Mydr [I] = aryline [I];
}
Mydt. Rows. Add (mydr );
}

Method 2: Read data as a data source. Common SQL statements can be executed.
Using (OleDbConnection conn = new OleDbConnection (@ "Provider = Microsoft. Jet. OLEDB.4.0; Data Source = C: csv; Extended Properties = Text ;"))
{
DataTable dtTable = new DataTable ();

OleDbDataAdapter adapter = new OleDbDataAdapter ("SELECT * FROM region test.csv]", conn );
Try
{
Adapter. Fill (dtTable );
}

Catch (Exception ex)
{
DtTable = new DataTable ();
}
This. GridView1.DataSource = dtTable;

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.