This question sort of encompasses two problems (which may very well be inter-related) that I have been having in C#. I really hope this hasn’t been clearly answered elsewhere, as I am unsure of what search terms to use and so far haven’t come across anything that has satisfactorily explained it to me. I have a function called isHighScore() in my C# word game. Basically what’s happening is that no matter the different ways I have tried formatting this, removing the usings, the try/catch’s, I seem to be unable to write the variable to the file. I have edited the code down significantly for anyone reading this for the first time in order illustrate what appears to be (for me) more of an issue with scope.
private void isHighScore() //Having problems...
{
string strHighScore;
try
{
StreamReader readHighScore = new StreamReader(strPath + "WAHS.txt")
strHighScore = readHighScore.ReadLine();
}
catch (Exception e)
{
MessageBox.Show(Convert.ToString(e.Message));
}
...
Next I would insert a similar block using StreamWriter and my comparison for userScore being greater than strHighScore doesn’t seem to evaluate true. Is it because my variable goes out of scope? How can I read the changed value outside of the scope of that try-catch, or for that matter, a using statement with StreamReader (which I know is the preferred method).
I’d strongly urge you to get rid of the manual calls to
Closeentirely. Useusingstatements instead. In fact, you don’t need theStreamReaderat all, if you use convenience methods provided byFile:Any exceptions thrown by the above code should probably be caught and handled elsewhere, higher up the stack.
(Note that your current code would just write the existing high score back to the file, not the new one.)
If you’re confident the file would only contain that line of text, you could just use
File.ReadAllTextinstead.Addressing the fundamental issue behind your confusion is possibly more important though. Do you understand why you can’t access
readHighScorein the place you’re trying to close it?