Reputation: 8115
In Java, when I want to start a process, I can just tell it the commands to run:
String[] commands = {"Perl", "-e", "print \"hello world\""}
ProcessBuilder processBuild = new ProcessBuilder();
processBuild.command(commands);
In C#, I have a problem because I need to do the same thing but I have to fill out filename
and arguments
separately as individual strings:
processBuild.FileName = commands[0];
for (int x = 1; x < commands.Length; x++)
{
processBuild.Arguments += " " + commands[x];
}
Now I don't know what the user is going to be trying to invoke, so I can't tailor this to fit the intended program. The problem with my above solution is that the process tries to run perl -e print "hello world"
. Why does it force me to treat this like a command line?
Of course I can't do something like if !start with [-/] { Surround with quotes }
because then something like "cmd /c echo hello" gets turned into cmd /c "echo" "hello"
. I mean I suppose I could make a bunch of if/elses and try to be smart about it, but there must be a better way?
So I turn to you guys to help me out. How can I kick off a process in C# that specifies its arguments in a non-cmd line fashion?
Upvotes: 2
Views: 1075
Reputation: 171246
The Process class used the CreateProcess API under the hood which is one of the lowest-level APIs available to start a process. This API separates executable from arguments, because it would have the same difficulties telling them apart as you do.
Two solutions:
Upvotes: 1