一分心灵的宁静

在滚滚红尘,繁杂人世里,能够保持一分心灵的宁静,随时回到自己的内心深处,细细品味生命的奥妙,无疑是一种修身养性的人生境界

导航

读取文件并保本到DataTable(例.dat, .csv等)

Posted on 2006-12-19 12:36  有缘无份  阅读(519)  评论(1编辑  收藏  举报
创建一个DataTable
1private DataTable TempTable()
2        {
3            DataTable oTable = new DataTable();
4            oTable.Columns.Add("Staff"typeof(System.String));
5            oTable.Columns.Add("Code"typeof(System.String));
6            oTable.Columns.Add("Date"typeof(System.String));
7            return oTable;
8        }
 1private void DataBinds(string staffCode)
 2        {
 3            string filename = txtDownloadFile.Text;
 4            if (File.Exists(filename))
 5            {
 6                FileAttributes attr = File.GetAttributes(filename);
 7                if (attr != FileAttributes.ReadOnly)
 8                {
 9                    dgUpdate.AutoGenerateColumns = false;
10                    dgUpdate.DataSource = ImportData(filename, staffCode);
11                }

12                else
13                {
14                    lblMessage.Text = "The file has already been imported.";
15                }

16            }

17            else
18            {
19                lblMessage.Text = "The selected file can not be loaded.";
20            }

21        }
读取文件里的数据并保存到DataTable
 1private DataTable ImportData(string filename, string staffCode)
 2        {
 3            DataTable result = new DataTable();
 4            //Import dat Data File
 5            StreamReader sr = new StreamReader(filename, System.Text.Encoding.GetEncoding("utf-8"));
 6            string linkText;
 7            string[] FieldText = null;
 8            DataSet dataSet = new DataSet();
 9            dataSet.Tables.Add(TempTable());
10            DataRow row;
11            while (sr.Peek() > -1)//StreamReader.Peek()
12            {
13                if (sr.Peek() == 1)
14                    continue;
15                row = dataSet.Tables[0].NewRow();
16                linkText = sr.ReadLine();
17                FieldText = linkText.Split(',');
18                row["Date"= FieldText[0];
19                if (staffCode == string.Empty)
20                {
21                    staffCode = FieldText[1]; ;
22                }

23                row["Staff"= staffCode;
24                row["Code"= FieldText[2];
25                dataSet.Tables[0].Rows.Add(row);
26
27                oTable = dataSet.Tables[0];
28                result = dataSet.Tables[0];
29            }

30            sr.Close();
31
32            return result;
33        }