2

I have been using external txt files to save the score and the player name (I only save one score and one name in two different files)

When there is a new highscore it saves over the old one. I had it all working perfectly until I published the project, now it cant locate the file.

I embedded the txt file but I cant write to it.

I am using the following code.

using (StreamWriter write = new StreamWriter(AppDomain.CurrentDomain.BaseDirectory + "highscore.txt"))  // read the high score text file
{
    write.WriteLine(player.score); // saves the new high score
    write.Close(); // closes the file
}
using (StreamWriter write = new StreamWriter(AppDomain.CurrentDomain.BaseDirectory + "nickname.txt")) // reads the high score text file
{
    write.WriteLine(player.nickname); // save new highscore name
    write.Close(); // close file
}

When I run the games from a USB or a CD they wont read -

So my question is - how to I place the txt files into a directory my game can see/find?

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
  • You need to store your folder/file to SpecialFolder.. pls see this answer http://stackoverflow.com/questions/16500080/how-to-create-appdata-folder-with-c-sharp – Amitd May 02 '15 at 07:18

1 Answers1

4

When you are running your program from the CD, your application's path is on that CD, so the code:

AppDomain.CurrentDomain.BaseDirectory + "highscore.txt"

points to a readonly CD path.

in order to be able to save the file properly, you can:

  • ask user to enter a path to which he/she wants the data to be saved
  • use one of the available directories (look in the Environment class), for instance using the:

    Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData)

Please also note that it is better to use Path.Combine() to concat the paths rather than '+' sign.

Piotr Piotr
  • 213
  • 2
  • 7