启动进程问题

6

我正在使用VSTS 2008 + C# + .Net 3.5开发控制台应用程序。我想从我的C#应用程序启动一个外部进程(一个exe文件),并且希望当前的C#应用程序被阻塞,直到外部进程停止,同时我也想获取外部进程的返回代码。

有什么好的实现方法吗?如果有示例代码将不胜感激。

3个回答

9
using (var process = Process.Start("test.exe"))
{
    process.WaitForExit();
    var exitCode = process.ExitCode;
}

1
同时将 process 包装在 using 块中也会有所帮助 :) - GSerg

2
    public static String ShellExec( String pExeFN, String pParams, out int exit_code)
    {
        System.Diagnostics.ProcessStartInfo psi = new System.Diagnostics.ProcessStartInfo(pExeFN, pParams);
        psi.RedirectStandardOutput = true;
        psi.UseShellExecute = false; // the process is created directly from the executable file
        psi.CreateNoWindow = true;

        using (System.Diagnostics.Process p = System.Diagnostics.Process.Start(psi))
        {
            string tool_output = p.StandardOutput.ReadToEnd();
            p.WaitForExit();
            exit_code = p.ExitCode;

            return tool_output;
        }
    }


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接