Sign in to follow this  
robertosaget

writing and reading to and from a text file in xna

Recommended Posts

robertosaget    106
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

Share this post


Link to post
Share on other sites
JamesSmith911    100
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...);
}
}

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this