码迷,mamicode.com
首页 > 其他好文 > 详细

TXT文件转换成DataSet数据集

时间:2014-09-18 22:15:55      阅读:145      评论:0      收藏:0      [点我收藏+]

标签:style   blog   color   os   ar   for   文件   数据   div   

 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        }  

 

TXT文件转换成DataSet数据集

标签:style   blog   color   os   ar   for   文件   数据   div   

原文地址:http://www.cnblogs.com/wingler/p/3980084.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!