2

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.

4
  • 1
    where is the loop? You might want to start the process asynchronously? Commented Jul 19, 2010 at 20:55
  • 2
    Also, you forgot to ask a question. Commented Jul 19, 2010 at 20:56
  • 2
    That code can't cause a loop unless your program is called "myprogram.exe". Commented Jul 19, 2010 at 20:56
  • 1
    Your if is completely useless. Commented Jul 19, 2010 at 20:57

3 Answers 3

3

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());
Sign up to request clarification or add additional context in comments.

1 Comment

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

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

2 Comments

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

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

2 Comments

Close() only releases resources, it doesn't terminate the process.
This is a console program. What happens is that console is opened and closed repeatedly without stopping.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.