Gotts
Gotts

Reputation: 2424

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#. 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. 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. 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.

enter image description here

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

Upvotes: 0

Views: 1464

Answers (1)

Sasha Alperovich
Sasha Alperovich

Reputation: 382

Probably missing:

p.BeginErrorReadLine();

And note that sb.AppendLine(args.Data); is not thread safe, consider synchronizing the access

Upvotes: 2

Related Questions