C#.bat文件执行错误&输出重定向

时间:2012-06-24 12:48:13

标签: c# batch-file exe

我有一个.bat文件要执行。

.bat文件中,最后是代码

START _file_creator.bat %some_arg_name%
ENDLOCAL
EXIT

我不想在执行期间显示窗口,而且我必须等到此.bat文件执行的操作完成后再终止执行(在操作结束时我看到标准文本“按任意键继续”)。我还需要检查该文件的输出和错误,所以我正在尝试使用该代码:

        System.Diagnostics.Process proc = new System.Diagnostics.Process();
        proc.StartInfo.FileName = @"C:\m_f\_config.bat";
        proc.StartInfo.RedirectStandardError = true;
        proc.StartInfo.RedirectStandardOutput = true;
        proc.StartInfo.UseShellExecute = false;
        proc.StartInfo.CreateNoWindow = true;

        proc.Start();
        proc.WaitForExit();
        output1 = proc.StandardError.ReadToEnd();
        proc.WaitForExit();
        output2 = proc.StandardOutput.ReadToEnd();
        proc.WaitForExit();

但我得到的只是错误

Windows can not find file "_file_creator.bat".
Make sure you typed the name correctly and try again.

当然,如果我使用.bat运行proc.StartInfo.UseShellExecute = true文件,它可以正常工作,但在这种情况下,我无法设置RedirectStandardError = trueRedirectStandardOutput = true

如何解决?

修改

使用该代码现在可以使用

 proc.StartInfo.FileName = @"C:\m_f\_config.bat";
 proc.StartInfo.WorkingDirectory = @"C:\m_f\";

1 个答案:

答案 0 :(得分:3)

尝试正确设置工作目录,或确保_file_creator.bat位于PATH的某个位置。请结合UseShellExecute

查看有关工作目录的documentation
  

WorkingDirectory属性的行为有所不同,具体取决于 UseShellExecute 属性的值。 UseShellExecute true 时,WorkingDirectory属性指定可执行文件的位置。如果WorkingDirectory是空字符串,则假定当前目录包含可执行文件。

     

UseShellExecute false 时,WorkingDirectory属性不会用于查找可执行文件。相反,它仅由启动的进程使用,并且仅在新进程的上下文中具有意义。当 UseShellExecute false 时,FileName属性必须是可执行文件的完全限定路径。