Sunday, August 19, 2007

Starting an external program from C# procedure

We are working on Source Control integration for GenWise and needed some code to start an external process, and read the output or errors from the process. After some trials we found this is the best way to do it:

System.Diagnostics.Process proc = new System.Diagnostics.Process();
proc.StartInfo.WorkingDirectory = this.WorkingFolder;
proc.StartInfo.CreateNoWindow = true;
proc.StartInfo.UseShellExecute = false;
proc.StartInfo.RedirectStandardOutput = true;
proc.StartInfo.RedirectStandardError = true;
proc.StartInfo.FileName = this.VSSClientProgram;
proc.StartInfo.Arguments = pArguments;
proc.Start();
string output = proc.StandardOutput.ReadToEnd();
string Error = proc.StandardError.ReadToEnd();
int ExitCode = proc.ExitCode;
proc.Close();

The CreateNoWindow sees to it that you will not see some Window popping up from your own program normally with no contents. The UseShellExecute = false makes it so you can redirect the standard outpout, input and error streams.

No comments: