2

我一直在使用外部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 文件放入我的游戏可以看到/找到的目录中?

4

1 回答 1

4

当您从 CD 运行程序时,您的应用程序的路径在该 CD 上,因此代码:

AppDomain.CurrentDomain.BaseDirectory + "highscore.txt"

指向只读 CD 路径。

为了能够正确保存文件,您可以:

  • 要求用户输入他/她希望保存数据的路径
  • 使用可用目录之一(查看 Environment 类),例如使用:

    Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData)

另请注意,最好使用Path.Combine()连接路径而不是“+”号。

于 2015-05-02T07:16:26.537 回答