【问题标题】:how to properly set process WorkingDirectory in C#如何在 C# 中正确设置进程 WorkingDirectory
【发布时间】:2015-08-09 14:25:24
【问题描述】:

在设置流程时,我似乎没有以正确的方式使用该变量 WorkingDirectory。我得到了错误(有问题)

ApplicationName='Test.exe', CommandLine='/d=1', CurrentDirectory='C:\Users\mb\Desktop\Integration\Tests\dailyTest\dailyTest\bin\Debug\Stress', Native error=系统找不到指定的文件。

但是在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 影响,但我尊重这一点。

【问题讨论】:

  • 向我们展示您用于创建流程的代码。
  • 看原帖!!
  • 尝试使用工作目录而不是只使用文件名的整个路径
  • 我会使用整个路径作为文件名,还包括工作目录。对于这两个,我会使用 Path.Combine 来构建路径。
  • 不要做Directory.GetCurrentDirectory() + "\\" + "Stress",这就是Path.combine存在的原因。

标签: c# process


【解决方案1】:

设置后尝试添加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 ?它们不一样吗?
  • 我做这个字符串 b = Path.Combine (proc.StartInfo.WorkingDirectory, proc.StartInfo.FileName); if (File.Exists( b )) { b = ""; } proc.Start();它说路径存在,因为它在 if 中。然后当我启动该过程时,它说: Native error= The system cannot find the file specified.
【解决方案2】:

发现我的错误:

我在Linux上,所以我需要指定我的exe文件由“mono”执行

process.FileName = "mono"
process.Argument = "nameOfExe param1 param2..."

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-05-26
    • 1970-01-01
    • 1970-01-01
    • 2020-02-07
    • 2012-08-25
    • 1970-01-01
    • 2020-10-31
    • 1970-01-01
    相关资源
    最近更新 更多