1 /// <summary> 2 /// TXT文件转换成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 (StreamReader 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 line 24 string strRead=""; 25 // split the read line into string array 26 string[] strReadBuffer=null; 27 bool flag = true; 28 while (flag) 29 { 30 //read one line 31 strRead = reader.ReadLine(); 32 // if not null 33 if (!string.IsNullOrEmpty(strRead)) 34 { 35 // split into string array 36 strReadBuffer=strRead.Split(','); 37 // creat a new datarow object 38 DataRow dr = dt.NewRow(); 39 //copy strings into this datarow 40 for (int i = 0; i < fieldCount; i++) 41 { 42 dr[i] = strReadBuffer[i]; 43 } 44 // add this row into data reader 45 dt.Rows.Add(dr); 46 } 47 else 48 { 49 flag = false; 50 } 51 } 52 ds.Tables.Add(dt); 53 reader.Close(); 54 return ds; 55 } 56 57 }