1 /// <summary> 2 // TXT file to dataset 3 /// </Summary> 4 /// <Param name = "filepath"> </Param> 5 // <Param name = "tablename"> </param> 6 /// <returns> </returns> 7 private dataset textfileloader (string filepath, string tablename) 8 {9 10 dataset DS = new dataset (); 11 datatable dt = new datatable (tablename); 12 13 filestream FS = file. open (filepath, filemode. open, fileaccess. read); 14 using (Stream Reader reader = new streamreader (FS, system. text. encoding. getencoding ("UTF-8") 15 {16 // int fieldcount = 0; 17 string [] headers = reader. readline (). split (','); 18 int fieldcount = headers. length; 19 for (INT I = 0; I <fieldcount; I ++) 20 {21 DT. columns. add (New datacolumn (headers [I], typeof (string); 22} 23 // read one line24 string strread = ""; 25 // split the Read line into string array26 string [] Strreadbuffer = NULL; 27 bool flag = true; 28 while (FLAG) 29 {30 // read one line31 strread = reader. Readline (); 32 // if not null33 if (! String. isnullorempty (strread) 34 {35 // split into string array36 strreadbuffer = strread. split (','); 37 // creat a new datarow object38 datarow DR = DT. newrow (); 39 // copy strings into this datarow40 for (INT I = 0; I <fieldcount; I ++) 41 {42 Dr [I] = strreadbuffer [I]; 43} 44 // Add this row into data reader45 DT. rows. add (DR); 46} 47 else48 {49 flag = false; 50} 51} 52 Ds. tables. add (DT); 53 reader. close (); 54 return Ds; 55} 56 57}
Convert a TXT file to a dataset Dataset