C# 为什么我的StreamReader不能工作?

C# 为什么我的StreamReader不能工作?,c#,C#,可能重复: 好的,我仍然在做一个掷骰子程序,每次游戏重新开始时,我都需要这个程序来显示之前的高分。但是当我输入代码时。它给我留下了错误。名称“File”不存在,找不到命名空间名称StreamReader? 请帮忙 private void button2_Click(object sender, EventArgs e) { try { int scores; int highscore = 0; StreamReader

可能重复:

好的,我仍然在做一个掷骰子程序,每次游戏重新开始时,我都需要这个程序来显示之前的高分。但是当我输入代码时。它给我留下了错误。名称“File”不存在,找不到命名空间名称StreamReader? 请帮忙

private void button2_Click(object sender, EventArgs e)
{   
    try
    {
        int scores;
        int highscore = 0;
        StreamReader inputFile;

        inputFile = File.OpenText("HighScore.txt");

        while (!inputFile.EndOfStream)
        {
            scores = int.Parse(inputFile.ReadLine());

            highscore += scores;
        }

        inputFile.Close();

        highscoreLabel.Text = highscore.ToString("c");

    }   
    catch (Exception ex)
    {
        MessageBox.Show(ex.Message);
    }
}

可能您还没有添加名称空间导入

using System.IO;
作为替代方案,您可以将完全限定引用写入文件和StreamReader对象

 System.IO.StreamReader inputFile;
 inputFile = System.IO.File.OpenText("HighScore.txt");
但是,这当然不是很方便

另外,请注意,如果出于任何原因,您的代码在读取流时抛出异常,那么该方法将在不关闭流的情况下退出。这应该不惜一切代价避免。
可能会有帮助

int scores;
int highscore = 0;
using(StreamReader inputFile = File.OpenText("HighScore.txt"))
{
    try
    {
         while (!inputFile.EndOfStream)
         {
             scores = int.Parse(inputFile.ReadLine());
             highscore += scores;
         }
         highscoreLabel.Text = highscore.ToString("c");
     }
     catch (Exception ex)
     {
         MessageBox.Show(ex.Message);
     }
}   

您是否已使用System.IO添加了
作为导入的命名空间?我同意@Steve可能是您真正需要投资的工具,如Resharper。它将为您节省许多前往SO的行程。