2010-03-01 34 views
6

我使用VSTS 2008 + C#+ .Net 3.5開發控制檯應用程序。我想從我的C#應用​​程序啓動一個外部進程(一個exe文件),並且我希望當前的C#應用​​程序被阻塞,直到外部進程停止,我也想獲得外部進程的返回碼。啓動過程問題

任何想法如何實現?欣賞一些示例代碼。

回答

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

添加一些異常處理代碼可以做的更好。 :) – 2010-03-01 08:13:09

+1

也''過程'包裹'使用'塊將幫助:) – GSerg 2010-03-01 08:20:22

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; 
     } 
    }