Convert a TXT file to Dataset

Source: Internet
Author: User
If you need to convert the TXT file to the dataset of the memory table, the TXT file is in a specific format, In the file, a record is a line, and the field is | "Split ( Note: after the last field "| ") Each field is the corresponding field in the database in sequence.
Example:
ID Number | line code | Station Encoding | Running Mode | mode setting date | mode setting time
1 | 98 | 9821 | 06 | 20070913 | 211835 |
The method is as follows:

/**/ /**/ /**/ ///   <Summary>
/// File Loading
///   </Summary>
///   <Param name = "filepath"> Path with file name </Param>
///   <Param name = "tablename"> Custom table name </Param>
///   <Param name = "fieldsinarray"> Custom table fields </Param>
///   <Returns> Dataset </Returns>

Public   Static Dataset textfileloader ( String Filepath, String Tablename, String [] Fieldsinarray)
{
Dataset DS =   New Dataset ();
Datatable dt =   New Datatable (tablename );

Filestream FS = File. Open (filepath, filemode. Open, fileaccess. Read );
Streamreader SR =   New Streamreader (FS );

For ( Int I =   0 ; I < Fieldsinarray. length; I ++ )
{
DT. Columns. Add (NewDatacolumn (fieldsinarray [I],Typeof(String)));
}

String Strread;
Bool Flag =   True ;

While (FLAG)
{
Strread = Sr. Readline ();

If ( ! String . Isnullorempty (strread ))
{
String [] Aryvale = Strread. Split ( ' \ T ' );

Datarow Dr = DT. newrow ();
For ( Int K =   0 ; K < Aryvale. length; k ++ )
{
Dr [fieldsinarray [k]=Aryvale [k];
}
DT. Rows. Add (DR );
}
Else
{
Flag= False;
}
}

DS. Tables. Add (DT );
Return DS;

}

Private void button2_click (Object sender, eventargs E)
{

String [] fieldsinarray = {"C0", "C1", "C2", "C3", "C4", "C5", "C6", "C7 "};

Dataset DS = new dataset ();

DS = textfileloader (@ "D: \ cpbuyaa20071018.txt", "good", fieldsinarray );
Datagridview1.datasource = Ds. Tables [0];

}

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.