gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 22:01:25 25 4
gpt4 key购买 nike

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

关于c# - 如何从文本文件中提取数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9950445/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com