适当设置进程工作目录

6
在设置进程时,似乎我没有以正确的方式使用变量"WorkingDirectory"。我会收到以下错误信息(包含一个catch):
ApplicationName='Test.exe',CommandLine='/d=1',CurrentDirectory='C:\Users\mb\Desktop\Integration\Tests\dailyTest\dailyTest\bin\Debug\Stress',Native error=The system cannot find the file specified.
然而,在文件夹"Stress"中确实存在一个"Test.exe",所以我真的不理解这意味着什么。
为什么会出现失败,如何解决?
代码如下(请注意,我已经将变量替换为直接字符串内容,以便更好地理解)。
Process proc = new System.Diagnostics.Process();

proc.StartInfo.WorkingDirectory = Directory.GetCurrentDirectory() + "\\" + "Stress");
proc.StartInfo.FileName = "Test.exe";
proc.StartInfo.Arguments = "/d=1";
proc.StartInfo.UseShellExecute = false;
proc.StartInfo.RedirectStandardOutput = false;
proc.Start ();
proc.WaitForExit();

return proc.ExitCode;

我知道WorkingDirectory受UseShellExecute的影响,但我尊重它。


5
给我们展示你用来创建进程的代码。 - Yuval Itzchakov
see the original post!! - Nissa Armelon
2
不要使用 Directory.GetCurrentDirectory() + "\\" + "Stress",这就是为什么 Path.combine 存在的原因。 - BCdotWEB
@NissaArmelon 你确定生成的路径存在吗? - Yuval Itzchakov
所有的都说它们存在,但我总是收到错误提示说找不到文件。 - Nissa Armelon
显示剩余3条评论
2个回答

0

在设置工作目录后,尝试添加Directory.Exists(proc.StartInfo.WorkingDirectory)Test.exe是否存在于该目录中?

还可以尝试:

string filename = Path.Combine( Directory.GetCurrentDirectory(), "Stress", "test.exe" );

check File.Exists( filename );

或许可以使用 filename 作为 proc.StartInfo.FileName

对于您的工作目录,请使用:Path.Combine(Directory.GetCurrentDirectory(), "Stress")

为了澄清,我建议使用:

proc.StartInfo.WorkingDirectory = Path.Combine( Directory.GetCurrentDirectory(),  "Stress");
proc.StartInfo.FileName = Path.Combine( Directory.GetCurrentDirectory(),  "Stress", "Test.exe" );
bool folderExists = Directory.Exists( proc.StartInfo.WorkingDirectory );
bool fileExists = File.Exists( proc.StartInfo.FileName );

你可以进行调试,查看文件和文件夹是否存在。

尝试了所有方法后,这是结果。按照您的建议,它们都存在。然而,当我执行代码时,它仍然无法工作(即使File.Exists返回true),它会显示: CurrentDirectory='',Native error= Cannot find the specified file 为什么它说CurrentDirectory="",当我设置WorkingDirectory时?它们不是一样的吗? - Nissa Armelon
我执行以下代码:string b = Path.Combine(proc.StartInfo.WorkingDirectory, proc.StartInfo.FileName);如果 (File.Exists(b)) { b = ""; }proc.Start();它会输出路径存在,因为它进入了if语句。 然后当我启动进程时,它会输出以下信息:本机错误=系统找不到指定的文件。 - Nissa Armelon

0
发现了我的错误:
我在Linux上,所以需要指定我的exe文件由“mono”执行。
process.FileName = "mono"
process.Argument = "nameOfExe param1 param2..."

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接