简体   繁体   中英

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM