Anton P
Anton P

Reputation:

The system cannot find the file specified when running CMD.exe from C#

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?

Upvotes: 11

Views: 25754

Answers (7)

Alex dev
Alex dev

Reputation: 1

Easiest way is to add the program to the solution with ADD EXISTING ITEM and type

System::Diagnostics::Process::Start("ccsetup305.exe");

Upvotes: -1

zebrabox
zebrabox

Reputation: 5764

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"); 

Upvotes: 3

Matt Dearing
Matt Dearing

Reputation: 9386

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

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

Upvotes: 3

David Fullerton
David Fullerton

Reputation: 3254

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");

Upvotes: 11

Aaronaught
Aaronaught

Reputation: 122624

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.

Upvotes: 7

David
David

Reputation: 73564

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

Upvotes: 0

Benny
Benny

Reputation: 8815

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

Upvotes: 0

Related Questions