Sunday, February 20, 2005

Using System.Diagnostics to run external processes

[This was originally posted at http://timstall.dotnetdevelopersjournal.com/using_systemdiagnostics_to_run_external_processes.htm]

Sometimes you'll want to run an external program, like bat, exe, or vbs. I find this especially useful for testing and deployment - I'll want to reset IIS or run a VBScript that initializes the environment, or call osql (the command line for SQL Server) to run a database script. Fortunately .Net provides a great way to do this using the System.Diagnostics namespace.

The simplest approach is a static utility method that can take the filename and command line arguments ike so:

System.Diagnostics.Process.Start("Simple.bat", "arg1 arg2");

This opens up a console window and runs the command. While it works for simple things, such as resetting IIS, there's two additional useful features we may want to do, especially for quick-running processes: (1) Run the process in a hidden window, (2) Wait for the process to exit. We can do both of these with code like the following:

public static void RunHiddenConsole(string strFileName, string strArguments, bool blnWaitForExit) {    //run in process without showing dialog window:    ProcessStartInfo psi = new ProcessStartInfo();    //psi.CreateNoWindow = true;    psi.WindowStyle = ProcessWindowStyle.Hidden;    psi.FileName = strFileName;    psi.Arguments = strArguments;    Process p = System.Diagnostics.Process.Start(psi);    if (blnWaitForExit)        p.WaitForExit();} //end of method

To run the process in a hidden window, we create a ProcessStartInfo object and specify its window style to be Hidden. We can then pass this ProcessStartInfo into the Process.Start method. To wait for the exit, we create a process object from the Process.Start method, and use its WaitForExit method.

Note that this is very context-independent functionality, and is therefore great to put into your own utilities class that you can reuse from project to project.

No comments:

Post a Comment