C# 从文件中添加数字

C# 从文件中添加数字,c#,C#,我要做的是从text.txt文件中读取数字,并将它们相加 该文件包含 86 97 144 26 他们各自为政。我被难住了:我 这是我的代码: namespace CH13EX1 { class CH13EX1 { static void Main(string[] args) { // opens the file StreamReader inFile; // test

我要做的是从text.txt文件中读取数字,并将它们相加 该文件包含

86
97 
144 
26
他们各自为政。我被难住了:我

这是我的代码:

namespace CH13EX1
{
    class CH13EX1
    {
        static void Main(string[] args)
        {
            // opens the file
            StreamReader inFile;
            // tests to make sure the file exsits
            if (File.Exists("text.txt"))
            {
                // declrations
                string inValue;
                int total;
                int number;
                // makes infile the file 
                inFile = new StreamReader("text.txt");
                // loop to real the files
                while ((inValue = inFile.ReadLine()) != null)
                {
                    number = int.Parse(inValue);
                    Console.WriteLine("{0}", number);

                }
            }
        }
    }
}

对现有代码的最小更改是

int total = 0;
using(inFile = new StreamReader("text.txt"))
{
    while ((inValue = inFile.ReadLine()) != null)
    {   
        if(Int32.TryParse(inValue, out number))
        {
             total += number;
             Console.WriteLine("{0}", number);
        }
        else
            Console.WriteLine("{0} - not a number", inValue);
    }
}
Console.WriteLine("The sum is  {0}", total);
当然,从文件中读取的值应该添加到一个变量中,该变量保存单行上的值的运行总数,但是我添加了一个变量来检查您的数字是否真的是整数(如果Parse无法将字符串转换为整数值,它将引发异常)


此外,我还使用了打开文件并确保以正确的方式关闭和处理StreamReader

很好,它是否有效?您在哪行代码上遇到了难题?这里的许多专家都可以给您答案,但我觉得从长远来看,这对您没有帮助。看起来你已经完成了所有困难的部分。你到底在挣扎什么?泰,谢谢你解决了我的问题,我很感谢你提供的额外信息:使用简单的
文件.ReadLines
文件.ReadAllLines
也可以提高性能,避免任何
的东西。