在 .NET 中使用 System.Diagnostics.Process 可輕鬆啟動外部執行檔或命令列程式,並傳遞參數、設定工作目錄、視窗樣式等。
// 啟動命令提示字元
Process.Start("cmd.exe");
// 直接啟動執行檔
Process.Start(@"C:\Path\To\App.exe");
透過 ProcessStartInfo 設定檔名、參數、工作目錄、視窗樣式、是否使用 Shell 執行等:
System.Diagnostics.Process p = new System.Diagnostics.Process();
p.StartInfo.FileName = "arj.exe";
p.StartInfo.Arguments = "-x sourceFile.Arj c:\\temp";
p.Start();
if (p.HasExited) p.Kill();
public static bool StartProcess(string file, string workdirectory, string args, ProcessWindowStyle style)
{
try
{
Process myprocess = new Process();
ProcessStartInfo startInfo = new ProcessStartInfo(file, args);
startInfo.WindowStyle = style;
startInfo.WorkingDirectory = workdirectory;
myprocess.StartInfo = startInfo;
myprocess.StartInfo.UseShellExecute = false; // 重導向輸出時需設 false
myprocess.Start();
return true;
}
catch (Exception e0)
{
MessageBox.Show("啟動應用程式時出錯!原因:" + e0.Message);
}
return false;
}
string parms = GlobalObject.GetInstance().UserID + " " + GlobalObject.GetInstance().UserPassword;
if (PublicMethods.StartProcess(
Application.StartupPath + @"\uptool\uptool.exe",
Application.StartupPath + @"\UpTool",
parms,
ProcessWindowStyle.Normal))
{
Environment.Exit(0); // 啟動更新程式後結束自身
}
掌握 Process 類別,即可實現自動更新、外部工具整合、批次腳本執行等常見需求。