简体   繁体   English

在C#中运行批处理文件时捕获所有输出

[英]Capture ALL output when running batch file in c#

There are numerous examples out there which describe how to capture the standard and error output when running a batch file in c#. 有许多示例描述了在c#中运行批处理文件时如何捕获标准和错误输出。 I am following those instructions and while it captures MOST of the output it doesn't capture all. 我正在按照这些说明进行操作,尽管它捕获了大部分的输出,但并未捕获全部。 And I can't find any explanation or help in dealing with this. 而且我找不到任何解释或帮助解决此问题。

For example I have to run a command via a batch file to generate a PDF from Tableau. 例如,我必须通过批处理文件运行命令以从Tableau生成PDF。 All the resulting outputs are captured correctly including confirmation of login to the server, confirmation of which PDF will be generated etc. However when an error occurs the error is not captured. 正确捕获所有结果输出,包括确认登录到服务器,确认将生成PDF等。但是,当发生错误时,不会捕获错误。 However if I run the batch file manually (ie not via code) I can see the error message in the console. 但是,如果我手动运行批处理文件(即不通过代码),则可以在控制台中看到错误消息。 See screenshot below....you can see the command line calls and the server responses. 请参阅下面的屏幕截图。...您可以看到命令行调用和服务器响应。 But the most important information, the error message (highlighted) is not being captured when running via code. 但是,最重要的信息是通过代码运行时未捕获到错误消息(突出显示)。

在此处输入图片说明

Can anyone see anything to add to the following code snippet that would capture this information? 谁能看到任何要添加到以下代码段中以捕获此信息的内容吗? Or a reason why its not being captured?? 还是不被捕获的原因?

        System.Diagnostics.ProcessStartInfo procStartInfo = new 
        System.Diagnostics.ProcessStartInfo(batchFilePath + batchFileName);

        procStartInfo.RedirectStandardOutput = true;
        procStartInfo.RedirectStandardError = true;
        procStartInfo.UseShellExecute = false;
        procStartInfo.CreateNoWindow = true;
        Process p = new Process();
        p.EnableRaisingEvents = true;
        p.StartInfo = procStartInfo;
        p.StartInfo.CreateNoWindow = true;
        p.StartInfo.UseShellExecute = false;
        StringBuilder sb = new StringBuilder();    
        p.OutputDataReceived += (sender, args) => sb.AppendLine(args.Data);
        p.ErrorDataReceived += (sender, args) => sb.AppendLine(args.Data); ;
        p.Exited += Exited;
        p.Start();
        p.BeginOutputReadLine();

Appreciate any help on this! 感谢任何帮助! Thanks 谢谢

Probably missing: 可能丢失:

p.BeginErrorReadLine();

And note that sb.AppendLine(args.Data); 并注意sb.AppendLine(args.Data); is not thread safe, consider synchronizing the access 不是线程安全的,请考虑同步访问

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM