6

I'm trying to start a process which contains multiple spaces within the arguments. The arguments that are passed are dynamically built. For example:

// These three strings will be built dynamically
string consolePath = "C:\\My Path\\nunit3-console.exe"
string dll = "C:\\My Path\\My.Test.dll"
string where = "--where \"test == My.Test.Example \""

string cmdText = $" \"{consolePath }\" \"{dll}\" {where}";
//cmdText = "\"C:\\My Path\\nunit3-console.exe\" \"C:\\My Path\\My.Test.dll\" --where \"test == My.Test.Example \""

var processInfo = new ProcessStartInfo("cmd.exe", $"/c {cmdText}");
processInfo.CreateNoWindow = false;
Process process = Process.Start(processInfo);
process.WaitForExit();
process.Close();

This does not work as any text beyond the first space will be ignored. I will get a message such as 'C:\My' is not recognized as an internal or external command, operable program or batch file.

I tried adding parentheses around the arguments, as noted here, but it didn't work. What is the correct way to do this?

usr4896260
  • 1,427
  • 3
  • 27
  • 50

3 Answers3

4

You probably have to add a further double-quote around anything that may include spaces within one single argument. Usually a space means the end of an argument. So to preserve this, you´d have to put the string into double-quotes.

So consolePath should actually be this:

var consolePath = "\"C:\\My Path....exe\"";
MakePeaceGreatAgain
  • 35,491
  • 6
  • 60
  • 111
  • I changed it to `var processInfo = new ProcessStartInfo("cmd.exe", $"/c \"{cmdText}\"");` and it works perfectly. Thank you for clarifying. – usr4896260 Jan 29 '18 at 14:16
1

In addition to previous answer, @ could be used to avoid \\ like this:

@"""C:\My Path\nunit3-console.exe"""

or:

"\"" + @"C:\My Path\nunit3-console.exe" + "\""

More about @ here: What's the @ in front of a string in C#?

Alex
  • 790
  • 7
  • 20
0

After searching two days for working string I finally found it.

Just wrap string like this:

string Arguments = "/c ""path" --argument "";

string Arguments = "/c \""path" --argument \"";

Notice bold quotes from first string.

TJacken
  • 354
  • 3
  • 12