读写txt文件发布问题c#
reading and writing txt file publish problems c#
我一直在使用外部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 文件放入我的游戏可以 see/find 的目录中?
当您运行您的程序来自 CD 时,您的应用程序路径在该 CD 上,因此代码:
AppDomain.CurrentDomain.BaseDirectory + "highscore.txt"
指向只读 CD 路径。
为了能够正确保存文件,您可以:
- 要求用户输入 he/she 想要保存数据的路径
使用可用目录之一(查看环境 class),
例如使用:
Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData)
另请注意,最好使用 Path.Combine()
来连接路径而不是“+”号。
我一直在使用外部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 文件放入我的游戏可以 see/find 的目录中?
当您运行您的程序来自 CD 时,您的应用程序路径在该 CD 上,因此代码:
AppDomain.CurrentDomain.BaseDirectory + "highscore.txt"
指向只读 CD 路径。
为了能够正确保存文件,您可以:
- 要求用户输入 he/she 想要保存数据的路径
使用可用目录之一(查看环境 class), 例如使用:
Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData)
另请注意,最好使用 Path.Combine()
来连接路径而不是“+”号。