views:

105

answers:

3

I would like to execute a program in .NET server side code.

So far I have this:

    Process p = new Process();  
    p.StartInfo.FileName = "myProgram.exe";
    p.StartInfo.Arguments = " < parameter list here > ";
    p.Start();
    p.Close();

This is a console program. What happens is that console is opened and closed repeatedly without stopping.

+2  A: 

Check out the BackgroundWorker class. Here is a more detailed walkthrough/example of its use.

Josh Stodola
I'm not sure if this will help. There is no time consuming computation. This is a simple console program. When I run it, the console is opened and closed repeatedly without stopping.
dev.e.loper
@dev Just try it
Josh Stodola
Tried this. In DoWork function I'm creating and starting a process. RunWorkerCompleted function never gets called. I'm guessing it has something to do with me running a process in BackworkerProcess. There are no errors or exceptions thrown as far as I see.
dev.e.loper
A: 

That code will not produce an infinite loop. It will fire up a program, and then immediately close the process. (You might not want to close it, but rather wait for the process to end).

driis
Close() only releases resources, it doesn't terminate the process.
Hans Passant
This is a console program. What happens is that console is opened and closed repeatedly without stopping.
dev.e.loper
+1  A: 

You want,

Process p = new Process();  
    p.StartInfo.FileName = "myProgram.exe";
    p.StartInfo.Arguments = " < parameter list here > ";
    p.Start();
    p.WaitForExit();

what happens in your code is you start the process and you close it right away, what you need is call WaitForExit() which actually waits for the process to close on its own,

To Print the output before the app closes:

Process p = new Process();  
p.StartInfo.FileName = "myProgram.exe";
p.StartInfo.Arguments = " < parameter list here > ";
p.StartInfo.UseShellExecute = false;
p.StartInfo.RedirectStandardOutput = true;
p.Start();
p.WaitForExit();
Console.WriteLine(p.StandardOutput.ReadToEnd());
Keivan
I tried that and got same behavior.
dev.e.loper
in that case I'm thinking that the application that you are trying to run is terminating on it's own, try the code I added to my answer to get the output before the window closes.
Keivan