using System.Diagnostics;
Process ie = new Process();
ie.StartInfo.FileName = "iexplore.exe";
ie.StartInfo.Arguments = "https://www.example.com";
ie.Start();
| 成員 | 用途 |
|---|---|
StartInfo.FileName | 可執行檔路徑或註冊關聯的檔案/URL |
StartInfo.Arguments | 命令列參數 |
StartInfo.WorkingDirectory | 工作目錄 |
StartInfo.Verb | 動作:runas (管理員)、print、edit 等 |
StartInfo.WindowStyle | Hidden、Minimized、Maximized、Normal |
StartInfo.UseShellExecute | true (預設) 使用 Shell 執行,支援 Verb/URL;false 直接建立進程,支援重導向 I/O |
StartInfo.RedirectStandardOutput | 搭配 UseShellExecute=false 捕獲標準輸出 |
Start() | 啟動進程,回傳 bool 表示成功與否 |
WaitForExit() | 阻塞等待進程結束 |
ExitCode | 進程結束代碼 |
var psi = new ProcessStartInfo
{
FileName = "cmd.exe",
Arguments = "/c net stop wuauserv",
Verb = "runas", // 觸發 UAC
UseShellExecute = true // Verb 需要 ShellExecute
};
Process.Start(psi);
var psi = new ProcessStartInfo
{
FileName = "git.exe",
Arguments = "status",
UseShellExecute = false,
RedirectStandardOutput = true,
RedirectStandardError = true,
CreateNoWindow = true
};
using var proc = Process.Start(psi);
string output = proc.StandardOutput.ReadToEnd();
string error = proc.StandardError.ReadToEnd();
proc.WaitForExit();
Console.WriteLine($"ExitCode: {proc.ExitCode}\n{output}");
Process.Start(new ProcessStartInfo("https://docs.microsoft.com") { UseShellExecute = true });
Process.Start(new ProcessStartInfo(@"C:\Report.pdf") { UseShellExecute = true });
Process 類別僅限本機。遠端啟動需透過:
ManagementClass("Win32_Process").InvokeMethod("Create", ...) (需 RPC/DCOM 權限)Invoke-Command -ComputerName Server01 -ScriptBlock { Start-Process ... }FileName 請用完整路徑,參數含空白請用雙引號包裹。proc.WaitForExitAsync() (.NET 6+) 避免凍結介面。Process 實作 IDisposable,務必 using 或呼叫 Dispose()。StandardOutput 時若緩衝區滿會阻塞,請改用非同步事件 OutputDataReceived 或同時讀取 Output/Error。System.Diagnostics.Process 是 .NET 啟動與管理外部程序的核心 API,掌握 ProcessStartInfo 設定與 UseShellExecute 雙模式差異,即可涵蓋從簡單開啟網頁到複雜管線導向、提權執行、遠端協調等多數場景。