开发者

Running an executable programmatically .NET

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.


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


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


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜