The World’s Leading Microsoft .NET Magazine
   
 
timstall

Donate Today!

Search Box

 

Calendar

««Sep 2008»»
SMTWTFS
 
1
2
3
456
78910111213
14151617181920
21222324252627
282930

My RSS Feeds








Mailing List

Most Popular Tags

                                                           

Using System.Diagnostics to run external processes

posted Monday, 21 February 2005

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.

links: digg this    technorati    




1. a reader left...
Wednesday, 13 April 2005 4:53 pm

Great code snippit, thanks.

John


2. Tim Stall left...
Monday, 18 April 2005 11:38 am

Thanks for the feedback.


3. Ruwan left...
Tuesday, 20 September 2005 11:24 pm

This is greate, Thanks


4. Paul left...
Thursday, 23 February 2006 8:33 pm

Exactly What I Needed Got No Joy with SHELL Command.


5. Tommy left...
Thursday, 14 September 2006 4:54 pm

Awesome little piece of code here! This is exactly what I was looking for