System.Diagnostics.Process 類別提供啟動、監控、控制外部程序的完整功能。根據業務需求,主要有三種常用模式:
適用於獨立運行的工具、批次檔、文件開啟等場景:
Process.Start(@"C:\scripts\listfiles.bat");
主程式繼續執行,不等待子進程結束。
需等待子進程結束、讀取標準輸出、處理逾時:
var psi = new ProcessStartInfo(@"C:\scripts\listfiles.bat")
{
RedirectStandardOutput = true,
UseShellExecute = false, // 必須為 false 才能重導向
CreateNoWindow = true, // 隱藏視窗
};
var process = Process.Start(psi);
string output = process.StandardOutput.ReadToEnd();
bool exited = process.WaitForExit(2000); // 2 秒逾時
if (!exited)
{
process.Kill(); // 強制終止
throw new TimeoutException("子進程執行逾時");
}
Console.WriteLine(output);
關鍵點:UseShellExecute = false 是重導向輸入/輸出/錯誤流的前提;WaitForExit 避免無限阻塞。
Process.Start("https://www.example.com");
利用 Shell Execute 機制,系統會自動呼叫預設瀏覽器處理 HTTP/HTTPS 協定。
ProcessStartInfo.Arguments 設定命令列參數WorkingDirectory 指定子進程的當前目錄Verb = "runas" 以系統管理員權限啟動OutputDataReceived、ErrorDataReceived 並呼叫 BeginOutputReadLine() 實現即時流式讀取