我想出了如何使用StreamReader
来读取文本文件。现在我必须创建一个数组,并在价格index[1]
中合计所有的值。创建从使用StreamReader获得的数组和总值
我的数据如下:
黄色出租车,62.12,16年10月17日
福来鸡,9.50,16年10月18日
我目前只有10条线路,但是,未来可能会有更多的线路被添加。
我想在txtBox_Total.text = Total.ToString();
这里添加62.12和9.50,并进入总被我当前的代码:
private void btn_CalculateLoadExpenses_Click(object sender, EventArgs e)
{
string currentLine;
// Create StreamReader object to read Exams.txt
StreamReader examsReader = new StreamReader("TravelExpenses.txt");
listBox_Output.Items.Clear();
while (examsReader.EndOfStream == false)
{
currentLine = examsReader.ReadLine();
listBox_Output.Items.Add(currentLine);
}
}
'File.ReadAllLines'是一个容易得多如Damith的答案提示。如果你真的想在某种情况下使用'StreamReader',你应该在使用它之后关闭**阅读器,或者在'using'语句中包装流。 'File.ReadAllLines'会自动为你做这个。 – Jim
@Jim:在此期间更容易但更慢。 StreamReader更好。 – Transcendent
@Transcendent是的,这是正确的,我的评论并不意味着'File.ReadAllLines'更快。但事实上,值得一提的是赞成和反对者是什么。谢谢。 ...我不得不提这也取决于文件的大小。如果该文件仅包含例如20行......差异将会是* 0.007 ms *或多或少。 – Jim