0

我为我的游戏创建了一个高分文件,但我在阅读它时遇到了问题。

当我更换电脑时,我的 USB 驱动器将字母 .eg 从驱动器 E 更改为驱动器 G。

这会导致读取文件出现问题。(因为我使用字符串路径 = @"g:\Scores.txt";)

所以我的问题是....我可以设置程序位置的默认路径吗?

我当前的代码:-

string path = @"g:\Scores.txt";
            StringBuilder sb = new StringBuilder();
            using (StreamReader sr = new StreamReader(path))
            {
                while (sr.Peek() >= 0)
                {
                    sb.Append(sr.ReadLine());
                }
            }

任何帮助表示赞赏。

4

3 回答 3

3

游戏也在你的 U 盘上吗?您要将文件保存在与游戏相同的目录中,还是在它周围的某个目录中?做这样的事情:

using System;
using System.IO;
using System.Reflection;
...
string thisAsmFile = Assembly.GetExecutingAssembly().Location;
string thisAsmDir = Path.GetDirectoryName(thisAsmPath);
string highScoreFile = Path.Combine(thisAsmDir, "scores.txt");
于 2015-02-12T19:43:46.840 回答
0

如果您的程序与文件位于同一文件夹中(例如 in G:\),那么您可以简单地使用他的名称访问该文件:`path = "Scores.txt"。在这种情况下,无需知道文件在哪里

于 2015-02-12T19:44:51.440 回答
0

您应该使用您的应用程序路径,而不是绝对路径。你可以这样做:

using System.IO;
using System.Windows.Forms;

string appPath = Path.GetDirectoryName(Application.ExecutablePath);
于 2015-02-12T20:07:24.453 回答