0

目前我正在尝试为我的游戏编写一个启动器。我的问题是,如果你以这种方式启动我的游戏:

System.Diagnostics.Process.Start(@"F:\Freak Mind Games\Projects 2013\JustShoot\game.bat");

我收到未处理的异常或找不到错误。

但如果我这样做:

System.Diagnostics.Process.Start(@"game.bat");

有用。问题出在哪里?

4

1 回答 1

3

我假设批处理文件与您的程序启动器位于同一目录中。自动确定其位置:

string executableDir = Path.GetDirectoryName(Application.ExecutablePath);
Process.Start(Path.Combine(executableDir, "game.bat"));

在哪里

  • Application.ExecutablePath是您的可执行文件的路径,即 F:\Freak Mind Games\Projects 2013\JustShoot\justshoot.exe.

  • Path.GetDirectoryName(...)获取它的目录部分,即 F:\Freak Mind Games\Projects 2013\JustShoot.

  • Path.Combine(executableDir, "game.bat")将目录与game.bat, 即F:\Freak Mind Games\Projects 2013\JustShoot\game.bat


还要记住,从 Visual Studio 启动时,可执行路径是"...\bin\Debug""...\bin\Release". 因此,如果您的批处理文件位于项目目录中,您可能希望从路径中删除这些部分。

const string DebugDir = @"\bin\Debug";
const string ReleaseDir = @"\bin\Release";

string executableDir = Path.GetDirectoryName(Application.ExecutablePath);
if (executableDir.EndsWith(DebugDir)) {
    executableDir =
        executableDir.Substring(0, executableDir.Length - DebugDir.Length);
} else if (executableDir.EndsWith(ReleaseDir)) {
    executableDir =
        executableDir.Substring(0, executableDir.Length - ReleaseDir.Length);
}
Process.Start(Path.Combine(executableDir, "game.bat"));

更新

对目录进行硬编码不是一个好主意。将要启动的游戏的路径放在与游戏启动器相同的目录中的文本文件中(例如“launch.txt”)。每行将包含一个可以使用游戏名称及其路径启动的游戏。像这样:

Freak Mind Games = F:\Freak Mind Games\Projects 2013\JustShoot\game.bat
我的世界 = C:\Programs\Minecraft\minecraft.exe

在表单中将目录定义为变量:

private Dictionary<string,string> _games;

现在获取这些游戏的列表,如下所示:

string executableDir = Path.GetDirectoryName(Application.ExecutablePath);
string launchFile = Path.Combine(executableDir, "launch.txt"));

string[] lines = File.ReadAllLines(launchFile);

// Fill the dictionary with the game name as key and the path as value.
_games = lines
    .Where(l => l.Contains("="))
    .Select(l => l.Split('='))
    .ToDictionary(s => s[0].Trim(), s => s[1].Trim());

然后在 a 中显示游戏名称ListBox

listBox1.AddRange(
     _games.Keys
        .OrderBy(k => k)
        .ToArray()
);

最后启动选定的游戏

string gamePath = _games[listBox1.SelectedItem];
var processStartInfo = new ProcessStartInfo(gamePath);
processStartInfo.WorkingDirectory = Path.GetDirectoryName(gamePath);
Process.Start(processStartInfo); 
于 2013-04-16T19:25:58.343 回答