(1)弹出选择路径
从工具中拖出OpenFileDialog
在相应的点击事件中补一下两句代码
OpenFileDialog OpenFile = new OpenFileDialog();
OpenFile.ShowDialog();
就可以的到一个文件路径选择框了
另外说一下
fileName = OpenFile.FileName;//路径名
如果想要的到文件名需要加入一下两行代码
FileInfo myFile = new FileInfo(OpenFile.FileName);
FileName = myFile.Name; //所需无路径文件名
(2)读取文件并将数据存入一张表中
1.将文件变为流的形式
使用流逐行读取文件Path为文件路径
FileStream myfile = new FileStream(Path, FileMode.Open, FileAccess.Read);
StreamReader sr = new StreamReader(myfile, System.Text.Encoding.Default);
2.将数据流变为一张表
DataTable table = new DataTable();
table.Columns.Add("hourTime"); //年月日
able.Columns.Add("hourData"); //时值数据
while ((line = sr.ReadLine()) != null)
{
string[] b = line.ToString().Split(' ');//文件以什么进行分割
string hourData=null;
DataRow dr;//新建一个行
dr = table.NewRow();
++count;
string hourTime = line.Substring(0, 8);
hourData = line.Substring(11);
dr["hourTime"] = hourTime;//将所需要的数据相应塞到行中
dr["hourData"] = hourData;
table.Rows.Add(dr);
}
sr.Dispose(); //释放资源
sr.Close(); //必须释放资源