Search code examples
c#file-location

reading and writing txt file publish problems c#


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?


Solution

  • 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.