【问题标题】:.CMD execution in C# inexplicably failingC# 中的 .CMD 执行莫名其妙地失败
【发布时间】:2012-06-06 21:18:13
【问题描述】:

我正在尝试从 C# 程序执行 .cmd 进程。当我在命令行中运行该进程时,即

C:\Directory\Process.cmd  -x 1000 -y 1000 C:\Input\input.txt

我得到了适当的结果(在这种情况下,这意味着进程将文件写入:

C:\Output\output.txt

但是,当我尝试从简单的 C# 程序运行此过程时,不会创建输出文件。以下是我的一些尝试:

尝试 1)

try
{
    string processName = @"C:\Directory\Process.cmd";
    string argString = @" -x 1000 -y 1000 C:\Input\input.txt"; //The extra space in front of the '-x' is here on purpose
    Process prs = new Process();
    prs.StartInfo.UseShellExecute = false;
    prs.StartInfo.RedirectStandardOutput = false;
    prs.StartInfo.FileName = processName;
    prs.StartInfo.Arguments = argString;
    prs.StartInfo.WindowStyle = ProcessWindowStyle.Normal;

    prs.Start()
}
catch (Exception e)
{
    Console.Writeline(e.Message);
}

尝试 2)

try
{
    System.Diagnostics.Process.Start(@"C:\\Directory\\Process.cmd", " -x 1000 -y 1000 C:\\Input\\input.txt";
}
catch (Exception e)
{
    Console.Writeline(e.message);
}

现在,在这两种情况下,都不会引发异常,并且会访问 Process.cmd(它在 shell 中打印状态更新),但该进程不会创建任何输出文件。我尝试调用 Process.cmd 的方式是否有问题,直接从命令行运行时它可以正常工作,但当我尝试从我的 C# 程序调用它时它不能正常工作?

【问题讨论】:

  • 可以发一下process.cmd的内容吗?
  • 不幸的是我不能(我无权访问它)。不过,我知道 process.cmd 调用了一个处理数据并产生输出的 Java 应用程序。
  • 进程是否需要管理员权限才能执行和写入输出?您是否检查过 C# 程序是否以正确的权限运行?
  • 如果您正在运行批处理文件,UseShellExecute 不应该为真吗?
  • 能贴出生成Output.txt的代码吗?

标签: c# command-line process


【解决方案1】:

你这个?

System.Diagnostics.Process.Start("cmd.exe", @"/c C:\Directory\Process.cmd -x 1000 -y 1000 C:\Input\input.txt");

AFAIK,'@' 前置逐字字符串,不需要反斜杠掩码)

【讨论】:

    【解决方案2】:

    文件可能正在创建,但不是您想的那样。使用

    prs.StartInfo.WorkingDirectory = "yourpath"
    

    http://msdn.microsoft.com/en-us/library/system.diagnostics.processstartinfo.workingdirectory.aspx

    如果 UserName 和 Password 是,则必须设置 WorkingDirectory 属性 假如。如果未设置该属性,则默认工作目录为 %SYSTEMROOT%\system32。

    如果目录已经是系统路径变量的一部分,你可以 不必在此属性中重复目录的位置。

    在 UseShellExecute 时,WorkingDirectory 属性的行为有所不同 比 UseShellExecute 为假时为真。当 UseShellExecute 是 true,WorkingDirectory 属性指定 可执行。如果 WorkingDirectory 是一个空字符串,则当前 目录被理解为包含可执行文件。

    当 UseShellExecute 为 false 时,WorkingDirectory 属性不 用于查找可执行文件。相反,它被用于 已启动,并且仅在新流程的上下文中才有意义。

    在意识到路径作为参数传入并且可能对它写入的文件使用硬编码路径逻辑后,我删除了它,但由于评论引用了它,我将取消删除以防它仍然有帮助.

    【讨论】:

      【解决方案3】:

      所以我终于能够拿到源代码,并意识到问题出在 java 代码中......它将项目目录解释为输出目录。不过感谢大家的帮助,你们提供了一些非常有用的信息!

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-05-08
        • 2012-03-12
        • 1970-01-01
        • 2012-05-19
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多