我对C#很陌生,我正在尝试开发一个程序来分析计算时间。模拟程序的输出为4个过程提供了4个文件。 表单应该只显示以秒为单位的时间(这就是我获得regex.replace的原因)
到目前为止,这是我的一些代码。 我收到了一个错误"无法阅读封闭的文字阅读器"
private void btn_read_Click(object sender, EventArgs e)
{
string line;
OpenFileDialog openFileDialog1 = new OpenFileDialog();
openFileDialog1.Filter = "Log operation A files (*.lga)|*.lgf|Log operation B files (*.lgb)|*.lgb|Log operation C files (*.lgc)|*.lgc|Log operation D files (*.lgd)|*.lgd|All files (*.*)|*.*";
if (openFileDialog1.ShowDialog() == DialogResult.OK)
{
string path;
path = openFileDialog1.FileName;
StringBuilder str = new StringBuilder();
// Read the file and display it line by line.
System.IO.StreamReader file = new System.IO.StreamReader(path);
using (StreamReader sr = new StreamReader(path))
{
// Read the stream to a string, and write the string to the console.
line = sr.ReadToEnd();
while ((line = file.ReadLine()) != null)
{
if (line.Contains("Computation Time for part A Analysis ="))
{
txt_t_a.Text = Regex.Replace(line, @"[^0-9.]+", "");
}
file.Close();
}
}
}
}
}
}
答案 0 :(得分:0)
当您尝试阅读时,您正在关闭阅读器,从而导致出错。相关代码如下。移动关闭它应该停止给你这个错误。
using (StreamReader sr = new StreamReader(path))
{
// Read the stream to a string, and write the string to the console.
line = sr.ReadToEnd();
while ((line = file.ReadLine()) != null)
{
if (line.Contains("Computation Time for part A Analysis ="))
{
txt_t_a.Text = Regex.Replace(line, @"[^0-9.]+", "");
}
// Remove this line.
// file.Close();
}
// Put it here
file.Close()
}
// Or here
答案 1 :(得分:0)
删除此行:
System.IO.StreamReader file = new System.IO.StreamReader(path);
并更新:
using (StreamReader sr = new StreamReader(path))
{
// Read the stream to a string, and write the string to the console.
line = sr.ReadToEnd();
while ((line = sr.ReadLine()) != null)
{
if (line.Contains("Computation Time for part A Analysis ="))
{
txt_t_a.Text = Regex.Replace(line, @"[^0-9.]+", "");
}
sr.Close();
}
}