views:

352

answers:

3

The subject doesn't say much cause it is not easy to question in one line. I have to execute a few programs which I read from the registry. I have to read from a field where somebody saves the whole paths and arguments.
I've been using System.Diagnostics.ProcessStartInfo setting the name of the program and its arguments but I've found a wide variety of arguments which I have to parse to save the process executable file in one field and its arguments in the other.

Is there a way to just execute the whole string as is?

A: 

There are several, in fact.

  1. You can call cmd.exe with /C [your command line] as the arguments. This causes cmd.exe to process your command, and then quit.
  2. You could write the command to a batch file and launch that.

And of course there's the approach you're taking now, namely parsing the command line.

Michael Madsen
By option 1 you mean starting a ProcessInfo with cmd.exe as the filename and '/c <myargs>' as the arguments?
sebastian
I think you mean ProcessStartInfo, but yes, fill that in and pass it to Process.Start. You may want to set its UseShellExecute to false to run it in the background.If you don't need to hide the CMD.EXE window while the command is running, you can just use Process.Start("cmd.exe","/c "+myargs).
Michael Madsen
the cmd windows keeps open until the process ends
sebastian
+5  A: 

I have tackled this the same way as the poster above, using cmd.exe with process start info.

Process myProcess = New Process;
myProcess.StartInfo.FileName = "cmd.exe";
myProcess.StartInfo.Arguments = "/C " + cmd;
myProcess.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
myProcess.StartInfo.CreateNoWindow = True;
myProcess.Start();
myProcess.WaitForExit();
myProcess.Close();

cmd /c carries out the command, and then terminates. WaitForExit will terminate the process if it runs for too long.

deadcat
I works!I had to delete the waitforexit clause since I'm firing up the process from the UI thread. thanks +1 and answered
sebastian
A: 

When 'UseShellExecute' is not set, System.Diagnostics.Process calls either CreateProcess or CreateProcessAsUser to actually start a program (it uses the second one if you specify a user/domain/password). And both of those calls can take the command and file as a single argument. From MSDN:

The lpApplicationName parameter can be NULL. In that case, the module name must be the first white space–delimited token in the lpCommandLine string. ...

lpApplication name maps to ProcessStartInfo.Filename and lpCommandLine maps to Arguments. So you should be albe to just go:

var processStartInfo = new ProcessStartInfo()
{
    UseShellExecute = false,
    Arguments = cmd
};
Process.Start(processStartInfo);
Luke Quinane