首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> .NET 網頁程式設計 >> C# >> 關於C#

C# 關閉系統進程與啟動 CMD 執行命令兩種方案

     編輯:關於C#

方案一:透過 CMD 執行 ntsd 強制終止 (適用頑固進程)


string processName = "notepad"; // 目標進程名稱
Process[] procs = Process.GetProcessesByName(processName);
if (procs.Length == 0) return;

Process cmd = new Process();
cmd.StartInfo.FileName = "cmd.exe";
cmd.StartInfo.UseShellExecute = false;
cmd.StartInfo.RedirectStandardInput = true;
cmd.StartInfo.RedirectStandardOutput = true;
cmd.StartInfo.RedirectStandardError = true;
cmd.StartInfo.CreateNoWindow = true;
cmd.Start();

cmd.StandardInput.WriteLine($"ntsd -c q -p {procs[0].Id}");
cmd.StandardInput.WriteLine("exit");
cmd.WaitForExit();

原理:ntsd (Windows 偵錯工具) 以偵錯器身分附加進程並執行 q (quit) 命令,可終止普通 Kill() 無法結束的進程 (如系統關鍵進程、掛起進程)。

注意:需系統安裝 Debugging Tools for Windows (含 ntsd);Vista 以降版本可能需管理員權限。

方案二:標準 Process.Kill() (通用、簡潔)


string processName = "notepad";
Process[] procs = Process.GetProcessesByName(processName);
foreach (var p in procs)
{
    try { p.Kill(); }
    catch (Exception ex) { /* 記錄日誌: 權限不足、進程已結束等 */ }
}

優點:無外部依賴、程式碼簡單、.NET 內建。
缺點:受保護進程、關鍵系統進程、權限不足時會拋出例外。

進階:優雅關閉 (發送關閉訊息)


// 嘗試優雅關閉 (僅適用有視窗的進程)
foreach (var p in procs)
{
    if (p.CloseMainWindow()) 
    {
        if (!p.WaitForExit(3000)) // 等待 3 秒
            p.Kill(); // 強制終止
    }
    else
    {
        p.Kill(); // 無主視窗直接強制
    }
}

啟動 CMD 並執行命令通用封裝


public static string RunCmd(string command, int timeoutMs = 5000)
{
    using (Process p = new Process())
    {
        p.StartInfo.FileName = "cmd.exe";
        p.StartInfo.Arguments = $"/c {command}";
        p.StartInfo.UseShellExecute = false;
        p.StartInfo.RedirectStandardOutput = true;
        p.StartInfo.RedirectStandardError = true;
        p.StartInfo.CreateNoWindow = true;
        p.Start();
        string output = p.StandardOutput.ReadToEnd();
        string error = p.StandardError.ReadToEnd();
        p.WaitForExit(timeoutMs);
        return output + error;
    }
}

// 使用範例
string result = RunCmd("ipconfig /flushdns");

選擇建議

  • 一般應用程式關閉:CloseMainWindow() → Kill()。
  • 頑固/系統進程:嘗試 ntsd (需部署偵錯工具) 或要求使用者手動結束。
  • 執行命令列工具:使用 Process.StartInfo.Arguments="/c command" 模式,比重導向 StandardInput 更簡潔。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved