我正在尝试从文本文件中读取数字,每个数字都在它自己的行上。显示有多少个数字,并添加这些数字。到目前为止,这是我的代码。
private void readFileButton_Click(object sender, EventArgs e)
{
try
{
openFileDialog1.ShowDialog();
filePathReader = openFileDialog1.FileName;
//declare the variable to read the file
string numbersFromFile;
infile = File.OpenText(filePathReader);
//reads the contents
while (!infile.EndOfStream)
{
//get the numbers
numbersFromFile = infile.ReadLine();
//add numbers to the listBox
numbers.Items.Add(numbersFromFile);
}
numbers.Items.Add("How many numbers the file has and the Total of the random NUmbers");
//closethe file
infile.Close();
//Here I am supposed to display the total of the numbers there is a way to turn text data into int data
//and the total numbers the user wanted..say there are a total of blah random numbers
}
catch (Exception ex)
{
//display error message
MessageBox.Show(ex.Message);
}
答案 0 :(得分:1)
首先,如果您需要阅读整个文件,请一次性阅读整个文件。
var path = "myfile.txt";
var allLines = File.ReadAllLines(path);
var count = allLines.length;
var sum = allLines.Select(s=> int.Parse(s)).Sum();
答案 1 :(得分:0)
显示有多少个数字,
var numbers = new List<int>();
numbers.Add(int.Parse(numbersFromFile));
int count = numbers.Count;
并添加这些数字
int sum = numbers.Sum();
确保导入using System.Linq