writing and reading to and from a text file in xna
Hello,
Thanks for all the help on my project before. I now want to write to a text file so i can save high scores in the game. The problem is it crashes and i end the process but it ends to fast so i can not see the error. Here is what i want to do. At the end of a game write to the file "score.txt" and then load it later on. Here is what i did.
StreamWriter tw ;
protected override void Initialize()
{
tw = new StreamWriter("score.txt");
tw.Close();
tr = new StreamReader("score.txt");
tr.Close();
...
}
in the draw method there is a statement to see if you win if you , this executes
tw.Write(" ");
tw.Write(points.ToString());
tw.Close();
i am new to this and so far i had a lot of tutorials say different things.
So far it crashes when it reaches this point and i am not sure why. I made a console app that does this and it works fine but what am i doing wrong in my xna project where it does not write and it crashes? Should i post more code or is what i posted enough to show you what i did wrong? I have only had tutorials to go off of on how to do this.
Thanks
The problem is your StreamWriter is closed.
The way your code is written, you are creating a stream, closing it and then trying to write to it. You probably get this exception...
"Cannot write to a closed TextWriter."
I'd take the code out and check the high score in "Update" and write a helper method to output the score. Bear in mind that this is just a suggestion.
private void WriteHighScore()
{
using( System.IO.StreamWriter tw = new System.IO.StreamWriter("score.txt"))
{
tw.Write(" ");
tw.Write(whatever...);
}
}
The way your code is written, you are creating a stream, closing it and then trying to write to it. You probably get this exception...
"Cannot write to a closed TextWriter."
I'd take the code out and check the high score in "Update" and write a helper method to output the score. Bear in mind that this is just a suggestion.
private void WriteHighScore()
{
using( System.IO.StreamWriter tw = new System.IO.StreamWriter("score.txt"))
{
tw.Write(" ");
tw.Write(whatever...);
}
}
This topic is closed to new replies.
Advertisement
Popular Topics
Advertisement