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.
October 3, 2004
В·
Jouni Heikniemi В·
4 Comments
Posted in: .NET
4 Responses
Alan - December 5, 2004
How would I code it so it waits for the process to complete?
Jouni - December 5, 2004
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();
installer - November 23, 2009
does 'cmd.exe' and 'command.com' are the same file?
Layne Leadbetter - January 12, 2021
Hello there, have you by chance thought about to publish regarding Nintendo or PS handheld?
Leave a Reply