您的位置:首页 > 编程语言 > C#

c#读取txt文件并生成一张表

2017-01-12 10:59 316 查看

(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(); //必须释放资源
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  c# 读取txt文件