Skip to main content
 首页 » 编程设计

c#之如何从文本文件中提取数字

2024年02月23日21lhb25

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