C# Use Process.Start with parameters AND spaces in path

2.6k views Asked by At

I've seen similar examples, but can't find something exactly like my problem.

I need to run a command like this from C#:

ProcessStartInfo startInfo = new ProcessStartInfo();
startInfo.FileName = "cmd";
startInfo.Arguments = "/K D:\\as df\\solver\\Swag.Console.exe -f D:\\as df\\solver\\2035.swag -p 5555";
Process.Start(startInfo);

does not work.

startInfo.Arguments = "/K \"D:\\as df\\solver\\Swag.Console.exe\" -f D:\\as df\\solver\\2035.swag -p 5555";

does not work.

startInfo.Arguments = "/K \"D:\\as df\\solver\\Swag.Console.exe\" -f \"D:\\as df\\solver\\2035.swag\" -p 5555";

does not work.

startInfo.FileName = "\"D:\\as df\\solver\\Swag.Console.exe\"";
startInfo.Arguments = " -f \"D:\\as df\\solver\\2035.swag\" -p 5555";

so it works, but I want to CMD, is this possible?

enter image description here

1

There are 1 answers

0
rene On BEST ANSWER

The /K argument will execute the command that follows it. It can be a whole lot of commands chained with & but, and this is what you were missing in your attempts, they need to be fully enclosed in double quotes in that case. See the SS64 cmd reference

In other words, the command should look like this:

cmd /K " here what ever you want to execute"

Because of the forward and backslashes you quickly lose track. So I took out the outer double quotes wrapping a String.Format, so it becomes a bit more clear what your actual command should be like. Here is the code that I expect should work:

ProcessStartInfo startInfo = new ProcessStartInfo();
startInfo.FileName = "cmd";
startInfo.Arguments = String.Format(
    "/K \"{0}\"", 
    " \"D:\\as df\\solver\\Swag.Console.exe\" -f \"D:\\as df\\solver\\2035.swag\" -p 5555");
Process.Start(startInfo);

If Swag.Console.Exe would simply dump its arguments to the console this would be the outcome:

-f
D:\as df\solver\2035.swag
-p
5555