Tutorial :Running an executable programmatically .NET



Question:

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.


Solution:1

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());  


Solution:2

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


Solution:3

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).


Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Previous
Next Post »