我一直使用外部txt文件来保存分数和玩家姓名(我只在两个不同的文件中保存一个分数和一个名称)
当出现新的高分时,它会优先于旧的高分。在我发布该项目之前,一切都运行得很好,但现在它无法找到该文件。
我嵌入了 txt 文件,但无法写入它。
我正在使用以下代码。
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
}
当我从 USB 或 CD 运行游戏时,它们无法读取 -
所以我的问题是 - 如何将 txt 文件放入我的游戏可以看到/找到的目录中?
最佳答案
当您从 CD 运行程序时,应用程序的路径位于该 CD 上,因此代码:
AppDomain.CurrentDomain.BaseDirectory + "highscore.txt"
指向只读 CD 路径。
为了能够正确保存文件,您可以:
- 要求用户输入他/她想要保存数据的路径
使用可用目录之一(查看环境类), 例如使用:
Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData)
另请注意,最好使用 Path.Combine()
来连接路径,而不是使用“+”号。
关于c# - C#读写txt文件发布问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29999485/