tags:

views:

883

answers:

6

I'm getting the error message when running the following code from a C# console program.

"The system cannot find the file specified"

Here is the code:

System.Diagnostics.Process.Start("C:\Windows\System32\cmd.exe /c");

Strangely when i omit the /c switch the command can run!?!

Any ideas what I'm doing wrong?

A: 

you need add @ before the path. like this: @"C:\Windows\System32\cmd.exe /c"

Benny
+2  A: 

There is an overload of start to take arguements. Use that one instead.

System.Diagnostics.Process.Start(@"C:\Windows\System32\cmd.exe",  "/c");
Matt Dearing
You are missing the `/` to the command line argument.
Oded
Updated, thanks!
Matt Dearing
A: 

I believe that the issue is you're attempting to pass an Argument (/c) as a part of the path.

The arguments and the file name are two distinct items in the Process class.

Try

System.Diagnostics.Process.Start("C:\Windows\System32\cmd.exe",  "/c");

http://msdn.microsoft.com/en-us/library/h6ak8zt5.aspx

David Stratton
+4  A: 

Well, for one thing, you're hard-coding a path, which is already destined to break on somebody's system (not every Windows install is in C:\Windows).

But the problem here is that those backslashes are being used as an escape character. There are two ways to write a path string like this - either escape the backslashes:

Process.Start("C:\\Windows\\System32\\cmd.exe", "/c");

Or use the @ to disable backslash escaping:

Process.Start(@"C:\Windows\System32\cmd.exe", "/c");

You also need to pass /c as an argument, not as part of the path - use the second overload of Process.Start as shown above.

Aaronaught
+5  A: 

Process.Start takes a filename as an argument. Pass the argument as the second parameter:

System.Diagnostics.Process.Start(@"C:\Windows\System32\cmd.exe", "/c");
David Fullerton
A: 

I can see three problems with code you posted:

1) You aren't escaping your path string correctly
2) You need to pass the /c argument seperately to the path you want to execute
3) You are assuming every machine this code runs on has a c:\windows installation

I'd propose writing it as follows:

string cmdPath = System.IO.Path.Combine(Environment.SystemDirectory,"cmd.exe");
System.Diagnostics.Process.Start(cmdPath, "/c"); 
zebrabox