Reputation: 1042
I have a .NET program that launches cmd.exe to execute another program, "MyProgam.exe". I do this instead of launching MyProgram.exe because I need to run that as Administrator as well as capturing its output.
Here's what I have:
Process process = new Process();
ProcessStartInfo startInfo = new ProcessStartInfo();
startInfo.FileName = "cmd.exe";
string args =
@"/C ""C:\Program Files (x86)\MyFolder\MyProgram.exe"" ""arg1"" ""arg2"" > out.txt 2>&1";
startInfo.Arguments = args;
process.StartInfo = startInfo;
process.Start();
However, the output (as captured in output.txt) is:
'C:\Program' is not recognized as an internal or external command, operable program or batch file.
So it appears as though the quotes surrounding C:\Program Files (x86)\MyFolder\MyProgram.exe are ignored. I have tried to wrap it in an extra pair of quotes, like this:
@"/C """"C:\Program Files (x86)\MyFolder\MyProgram.exe"""" ""arg1"" ""arg2"" > out.txt 2>&1";
which then produces the following:
The filename, directory name, or volume label syntax is incorrect.
What am I missing?
Upvotes: 1
Views: 470
Reputation: 25351
According to CMD documentation:
If you specify /c or /k, cmd processes the remainder of string and quotation marks are preserved only if all of the following conditions are met:
• You do not use /s.
• You use exactly one set of quotation marks.
• You do not use any special characters within the quotation marks (for example: &<>( ) @ ^ |).
• You use one or more white-space characters within the quotation marks.
• The string within quotation marks is the name of an executable file.
If the previous conditions are not met, string is processed by examining the first character to verify whether or not it is an opening quotation mark. If the first character is an opening quotation mark, it is stripped along with the closing quotation mark. Any text following the closing quotation marks is preserved.
So you have to use one single pair of quotes to satisfy the conditions. If your arg1
and arg2
don't have spaces, only use quotes surrounding the path:
@"/C ""C:\Program Files (x86)\MyFolder\MyProgram.exe"" arg1 arg2 > out.txt 2>&1"
If your two arguments have spaces, you'll fall into the last paragraph (because you'll need to use more than one pair of quotes). You have to add quotes around each argument and also enclose theme altogether in an additional pair of quotes:
@"/C """"C:\Program Files (x86)\MyFolder\MyProgram.exe"" ""arg1"" ""arg2"""" > out.txt 2>&1"
Alternatively, enclose the arguments in parentheses which is valid batch and makes it a bit easier to read:
@"/C (""C:\Program Files (x86)\MyFolder\MyProgram.exe"" ""arg1"" ""arg2"") > out.txt 2>&1"
Upvotes: 1