如何从文本文件中提取数字
本文关键字:提取 数字 文件 文本 | 更新日期: 2023-09-27 18:29:38
在我按下按钮打开窗口选择文件之后;我不知道如何从实际文件或名为mystream的流中提取数字。
Stream myStream;
OpenFileDialog openFileDialog1 = new OpenFileDialog();
openFileDialog1.InitialDirectory = "c:''" ;
openFileDialog1.Filter = "txt files (*.txt)|*.txt|All files (*.*)|*.*" ;
openFileDialog1.FilterIndex = 2 ;
openFileDialog1.RestoreDirectory = true ;
if(openFileDialog1.ShowDialog() == DialogResult.OK)
{
if((myStream = openFileDialog1.OpenFile())!= null)
{
//Problem here: How do i extract the numerical values from my txt file or the stream called mystream.
// Insert code to read the stream here.
myStream.Close();
}
}
好吧,由于我们不知道您的输入格式(截至我写这篇文章时),很难告诉您如何准确地输出数字。
但以下是阅读文件每一行的大致要点。。。
if(openFileDialog1.ShowDialog() == DialogResult.OK)
{
if((myStream = openFileDialog1.OpenFile())!= null)
{
using (var reader = new StreamReader(myStream))
{
string line;
while ((line = reader.ReadLine()) != null)
{
// if it's one num per line, you can use Parse() or TryParse()
var num = int.Parse(line);
// otherwise, you can use something like string.Split() or RegEx...
}
}
}
}