C # Four Methods for reading CSV files

Source: Internet
Author: User
Code 1:

Use System. Web. UI. htmlcontrols. htmlinputfile to select the handle file.

The code in the button click event is used to read the file content after the file is selected.

1 system. Web. httppostedfile input = request. Files [0];
2
3 if (input! = NULL & input. contentlength! = 0)
4 {
5 string Path = input. filename. tostring ();
6 system. Io. streamreader reader = new system. Io. streamreader (PATH );
7
8 reader. Peek ();
9 While (reader. Peek ()> 0)
10 {
11 string STR = reader. Readline ();
12 string [] split = Str. Split (',');
13 if (split [0]! = "" & Split [1]! = "")
14 {
15 system. Data. dataset DS = new dataset ();
16 system. Data. datarow DR = Ds. Tables [0]. newrow ();
17 Dr [0] = Split [0];
18 Dr [1] = Split [1];
19 Ds. Tables [0]. Rows. Add (DR );
20}
21}
22}

Code 2:

Just now, read the table directly.

Select *
Into theimporttable
From
OpenRowSet ('msdasql ',
'Driver = {Microsoft text Driver (*. txt; *. CSV)}; defaultdir = D:; extensions = CSV ;',
'Select * From csvfile.csv ')

Code 3:

OpenRowSet ('msdasql ',
'Driver = {Microsoft text Driver (*. txt; *. CSV)}; defaultdir = D:; extensions = CSV ;',
'Select * From csvfile.csv ')

Complicated.

Files are operated as a database, using the OLE driver

Code 4:

1 int intcolcount = 0;
2 datatable mydt = new datatable ("mytablename");
3
4 datacolumn mydc;
5 datarow mydr;
6
7 string strpath = "";
8 string strline;
9 string [] aryline;
10
11 system. io. streamreader mysr = new system. io. streamreader (strpath);
12
13 while (strline = mysr. readline ())! = NULL)
14 {
15 aryline = strline. split (New char [] {'|'});
16
17 intcolcount = aryline. length;
18 for (INT I = 0; I 19 {
20 mydc = new datacolumn (aryline [I]);
21 mydt. columns. add (mydc);
22}
23
24 mydr = mydt. newrow ();
25 for (INT I = 0; I 26 {
27 mydr [I] = aryline [I];
28}
29 mydt. rows. add (mydr);
30}

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.