Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# run process with multiple spaces in arguments

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?

like image 257
usr4896260 Avatar asked Jan 29 '18 14:01

usr4896260


2 Answers

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\"";
like image 120
MakePeaceGreatAgain Avatar answered Oct 17 '22 11:10

MakePeaceGreatAgain


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#?

like image 1
Alex Avatar answered Oct 17 '22 13:10

Alex