October 03, 2004

Executing command line statements

Starting new tasks (other programs) in .net is actually very easy. You just have to find the Process class, which somewhat surprisingly resides in the System.Diagnostics namespace. Once you're there, a simple call will go far: Process.Start("notepad.exe") does what you'd expect. And because the Windows shell has some built-in logic for various cases, Process.Start("http://www.google.com/") pops up your default browser, too. Now that's cool.

What if you want to run something as if you had typed that into the command interpreter's prompt? The solution is equally easy, you just have to know a couple of things. First, the location (full pathname) of the command interpreter is located in the environment variable COMSPEC. Second, cmd.exe (the default command interpreter) accepts a /c parameter meaning "Run rest of the command line and then exit" - exactly what we want. The following helper method packs up this functionality:

public static void ExecThroughCmdShell(string command) {

  System.Diagnostics.Process.Start(
    Environment.GetEnvironmentVariable("COMSPEC"),
    " /c " + command
  );
}

Call the method with syntax like ExecThroughCmdShell("dir /s /p c:\\windows"); to have a new shell window pop up. If you need to wait for the task to return before continuing, the Start method returns a Process object which has a WaitForExit method just for this purpose.

Posted by Jouni Heikniemi at October 3, 2004 09:57 AM
.net

Comments

How would I code it so it waits for the process to complete?

Posted by: Alan at December 5, 2004 02:39 AM

Instead of using the static Process.Start, instantiate a new Process object, set the paths to the ProcessStartInfo object and call the non-static version of Process.Start. After that, call Process.WaitForExit; there is an overload with timeout and another without one. Some quick code, didn't test:

Process p = new Process();
p.StartInfo.Filename = Environment.GetEnvironmentVariable("COMSPEC");
p.StartInfo.Arguments = "/c dir";
p.Start();
p.WaitForExit();

Posted by: Jouni at December 5, 2004 06:40 AM

comment2, buy celtic woman dvd online, pmkjph, girlongi, 8-D, grandma anal movies, 9352, freedeerhuntingvideohunting, 338768,

Posted by: Kolt at July 1, 2008 06:49 AM
Post a comment









Remember personal info?