本方案不依賴第三方函式庫,而是利用 System.Diagnostics.Process 啟動系統已安裝的 WinRAR.exe,並傳遞命令列參數完成壓縮/解壓任務。關鍵在於從登錄表動態獲取 WinRAR.exe 完整路徑,避免硬編碼路徑導致部署失敗。
HKEY_CLASSES_ROOT\Applications\WinRAR.exe\shell\open\command 取得執行檔路徑,並移除參數佔位符 "%1"。ProcessStartInfo.WorkingDirectory 指定為目標輸出/來源資料夾,確保相對路徑正確。WindowStyle = ProcessWindowStyle.Hidden 避免彈出 WinRAR 介面干擾使用者。process.WaitForExit() 確保主程式等待壓縮完成再繼續。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);
}
}
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}\"。Process.Exited 事件配合 EnableRaisingEvents = true 實作非同步回呼。SharpCompress 或 SevenZipSharp。