joslinm
joslinm

Reputation: 8115

Specifying arguments in C# Process

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

Answers (1)

usr
usr

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:

  • Start cmd.exe as a process and hand your "command" as the argument to it. cmd.exe will do the parsing for you.
  • Do the parsing yourself although it is difficult.

Upvotes: 1

Related Questions