使用带空格的路径调用 ProcessStartInfo 总是中断

Calling ProcessStartInfo with a path with spaces always breaks

我正在调用具有以下配置的命令行程序:

var processStartInfo = new ProcessStartInfo {
    FileName = mainCommand,
    UseShellExecute = false,
    RedirectStandardOutput = true,
    RedirectStandardError = true,
    CreateNoWindow = true,
};

当我 运行 它与 mainCommand 是一条没有 space 的路径时它总是有效,如果路径上有 space失败的命令:

Could not find the command file at C:\Users\Some

实际路径是:

C:\Users\Some User\AppData\Local\Temp\Process.exe

那么,为什么它没有被转义,有什么方法可以转义这个路径名来防止这个错误吗?

尝试用引号括起来:

string targetExe = "\"C:\this path with spaces\helloWorld.exe\"";

它是这样工作的,但它也可以像帕特里克霍夫曼所说的那样工作而不必担心。您的系统似乎有些不同。

如果您想传递参数,请通过 ProcessStartInfo 中的 Arguments 进行。显然,如果它们也有空格(即:/arg1 "An Argument"),您必须将它们用引号括起来,如上所示。