Process.Start() Quips
It is more than a common requirement to be able to start another process from executing code. For instance, you might want to execute a batch file, run a command line utility of sorts, and so on. This is facilitated in the BCL through System.Diagnostics.Process class, more specifically, the Start method.
Process.Start("Notepad.exe");
You can also specify startup information like FileName, Argument, WindowStyle and so on, through the instance of another class called ProcessStartInfo.
ProcessStartInfo oStartInfo = new ProcessStartInfo();
oStartInfo.FileName = "Notepad.exe";
oStartInfo.Arguments = "MyWork.txt";
Process.Start(oStartInfo);
Simple. But there is a catch here. The instance of ProcessInfo bears a property called UseShellExecute. A value of true for this property would mean that the windows shell is used to start a process, and this is the default value. Therefore, you wouldn’t be able to extract the output or provide an alternative input for the process to be executed. This feature would be required, for instance, if you want to capture the output of a SQL script execution through osql.exe or as another example, the output of a command-line setup. So, to make this work, we need to set UseShellExecute to false and then, as required, set RedirectStandardInput (default is keyboard), RedirectStandardOutput (default is monitor), RedirectStandardError (default is monitor) properties to true. One thing to keep in mind, in this case is that, you should specifiy the full path of the executable or the path must be listed in the PATH environment variable. The code snippet given below captures the execution of a batch file and writes it to a log file:
Process runCmd = new Process();
runCmd.StartInfo.FileName = "RunBatch.bat";
runCmd.StartInfo.UseShellExecute = false;
runCmd.StartInfo.RedirectStandardOutput = true;
runCmd.Start();
FileStream fs = new FileStream("OutPut.log",FileMode.Append);
StreamWriter sw = new StreamWriter(fs);
sw.Write(runCmd.StandardOutput.ReadToEnd());
runCmd.WaitForExit();
sw.Close();
fs.Close();
Another simple tip is that, when UseShellExecute is true, you can start any document if its file type is associated with an executable that has the default action as open. For e.g. The following code launches test.txt in default text editor (notepad on my m/c)
ProcessStartInfo psi= new ProcessStartInfo(@"C:\test.txt");
Process.Start(psi);
You can say also associate verbs like Print etc.
ProcessStartInfo psi= new ProcessStartInfo(@"C:\test.txt");
psi.verb = "Print";
Process.Start(psi);
As another example, the following code launches the URL provided in the default browser.
Process.Start("http://www.microsoft.com");