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?
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\"";
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#?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With