如何从文本文件中提取数字

时间:2012-03-30 21:08:21

标签: c#

我按下按钮后打开一个窗口来选择文件;我不知道如何从实际文件或名为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();
    }
}

1 个答案:

答案 0 :(得分:4)

好吧,因为我们不知道你的输入格式(截至我写这篇文章的时候),很难告诉你如何准确地输出数字。

但是这里是阅读文件每一行的一般要点......

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...
            }
        }
    }
}