萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> 程式語言綜合

C# 呼叫 WinRAR 實現壓縮與解壓縮完整教學

核心架構:透過 Process 呼叫 WinRAR CLI

本方案不依賴第三方函式庫,而是利用 System.Diagnostics.Process 啟動系統已安裝的 WinRAR.exe,並傳遞命令列參數完成壓縮/解壓任務。關鍵在於從登錄表動態獲取 WinRAR.exe 完整路徑,避免硬編碼路徑導致部署失敗。

關鍵步驟解析

  1. 登錄表定位:讀取 HKEY_CLASSES_ROOT\Applications\WinRAR.exe\shell\open\command 取得執行檔路徑,並移除參數佔位符 "%1"。
  2. 工作目錄設定:ProcessStartInfo.WorkingDirectory 指定為目標輸出/來源資料夾,確保相對路徑正確。
  3. 隱藏視窗:設定 WindowStyle = ProcessWindowStyle.Hidden 避免彈出 WinRAR 介面干擾使用者。
  4. 同步等待:呼叫 process.WaitForExit() 確保主程式等待壓縮完成再繼續。

壓縮方法 (RAR)

public bool RAR(string sourcePath, string destDir, string rarName) {
    try {
        // 1. 從登錄表獲取 WinRAR.exe 路徑
        using (var regKey = Registry.ClassesRoot.OpenSubKey(@"Applications\WinRAR.exe\shell\open\command")) {
            string cmd = regKey.GetValue("").ToString(); // 格式: "C:\Path\WinRAR.exe" "%1"
            string rarExe = cmd.Substring(1, cmd.Length - 7).Trim('"'); // 擷取純路徑
            
            // 2. 確保來源目錄存在
            Directory.CreateDirectory(sourcePath);
            
            // 3. 建構壓縮指令: a (add) -r (recursive)
            string args = string.Format("a \"{0}\" \"{1}\" -r", rarName, sourcePath);
            
            // 4. 啟動進程
            var psi = new ProcessStartInfo(rarExe, args) {
                WorkingDirectory = destDir,
                WindowStyle = ProcessWindowStyle.Hidden,
                UseShellExecute = false
            };
            using (var proc = Process.Start(psi)) {
                proc.WaitForExit();
                return proc.ExitCode == 0;
            }
        }
    } catch (Exception ex) {
        // 建議記錄 Log 而非直接拋出
        throw new ApplicationException("RAR 壓縮失敗", ex);
    }
}

解壓縮方法 (UnRAR)

public bool UnRAR(string destPath, string rarDir, string rarName) {
    try {
        using (var regKey = Registry.ClassesRoot.OpenSubKey(@"Applications\WinRAR.exe\shell\open\command")) {
            string rarExe = regKey.GetValue("").ToString().Substring(1).Trim('"', ' ', '%', '1');
            
            Directory.CreateDirectory(destPath);
            
            // x (extract with full paths) -y (assume yes on all queries)
            string args = string.Format("x \"{0}\" \"{1}\" -y", rarName, destPath);
            
            var psi = new ProcessStartInfo(rarExe, args) {
                WorkingDirectory = rarDir,
                WindowStyle = ProcessWindowStyle.Hidden,
                UseShellExecute = false
            };
            using (var proc = Process.Start(psi)) {
                proc.WaitForExit();
                return proc.ExitCode == 0;
            }
        }
    } catch (Exception ex) {
        throw new ApplicationException("RAR 解壓縮失敗", ex);
    }
}

注意事項與優化建議

  • 例外處理:原碼 catch { throw e; } 會重置堆疊追蹤,應改為 throw; 或包裝為自訂例外。
  • 路徑含空白:參數路徑務必雙引號包裹 \"{path}\"。
  • 非同步需求:若 UI 需保持回應,可改用 Process.Exited 事件配合 EnableRaisingEvents = true 實作非同步回呼。
  • 依賴風險:目標機器必須預裝 WinRAR 且關聯正確;純 .NET 方案可考慮 SharpCompress 或 SevenZipSharp。
copyright © 萬盛學電腦網 all rights reserved