c# - C#读写txt文件发布问题

标签 c# file-location

我一直使用外部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/

相关文章:

c# - Entity Framework - 包含/引用/集合

c# - 如何计算 ListBox 中的重复项并在其旁边显示重复项的数量?

c# - ASP.NET MVC 中的后台线程 'job-queue'

python - 获取模块 py 文件路径的可靠方法

python - 如何使我的程序具有一致的初始当前工作目录?

javascript - 如何将变量作为字符串传递以定位要由 d3 读取的文件

c# - 如何从复杂的自适应卡中读取值?

c# - 带有 System.Text.Json 的可选属性的自定义 JSON 序列化程序

JAVA 文件编写器 : Get the path of created File using FileWriter

java - OSX/MacOS 相当于 Windows %PROGRAMDATA% 环境变量