简体   繁体   中英

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

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?

在此处输入图片说明

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 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM