开发者

Reporting back errors/failures from cmd files running under System.Diagnostics.Process

I'm currently working on an automated install system. The basics of how it works is that things needing to be installed are packaged along with a cmd file that governs the install. If it's an msi or an exe then the cmd file will tell it the installer the answers it needs, if it's a sql script it'll run it under sqlcmd and so on.

The cmd file is run through the following c# code:

        ProcessStartInfo p = new System.Diagnostics.Proces开发者_开发问答sStartInfo(filePath + fileToRun);
        p.WorkingDirectory = filePath;
        Process proc = new System.Diagnostics.Process();
        proc.StartInfo = p;

        proc.Start();
        proc.WaitForExit();

And that works well. It does what it's supposed to do.

However the problem I've got is that since this is automated and some components are dependent on the existence of previous components, it's critical that the system knows exactly what's been installed in a given environment and what isn't. So if the cmd file fails for some reason, my C# code needs to know about it.

I can't figure out how to do this. The System.Diagnostics.Process seems to isolate what it's running and has no idea what's going on inside the process that it's running. The error that indicates a failure could result from many sources - it could be the cmd file, or the sql script, or the installer or powershell.

So is there any way I can make my code recognise when an error has occurred in the process and record it? I can change the cmd files that run the code and try and pick up errors there, but I can't edit the files the cmd is trying to run. And even if I can isolate errors in the cmd file, how do I report them back to C#?

Cheers, Matt


You can redirect the error output of the process and use it in your application.

p.UseShellExecute = false; // necessary to redirect stderr
p.RedirectStandardError = true;

then

string error = proc.StandardError.ReadToEnd();
proc.WaitForExit();

Or, if you have control over it you could also pick some meaningful exit codes for failures in your process and then switch and them in your c# code. Something like...

switch (proc.ExitCode)
{
   case 1 : 
      // component A has failed
      break;
   case 2 : 
      // component B has failed
      break;
   default:
     // unknown error
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜