本文提供一個完整的 Cab 類別,封裝 Windows 原生 makecab.exe 與 expand.exe 命令列工具,實現 CAB 檔案的建立與解壓縮,適用於需要原生壓縮格式的部署場景。
namespace Com.ImYan.CabHelper
{
public class Cab
{
public string CabFileName { get; set; } // CAB 檔路徑
public List<string> FileList { get; set; } // 待壓縮/解壓檔案清單
private string TempDir; // 暫存目錄
public Cab() { /* 初始化暫存目錄 */ }
// 私有方法:建立 list.txt、執行 CMD 命令、移動產生的 CAB、分析解壓結果
private string CreateListFile() { ... }
private string RunCommand(string cmdString) { ... }
private void MoveCabFile() { ... }
private List<string> GetFilesFromDir(string dir) { ... }
private void GetExpandedFileByCmdResult(string cmdResult) { ... }
// 公用方法
public bool MakeCab(out string errorInfo) { ... } // 建立 CAB
public bool ExpandCab(out string errorInfo) { ... } // 解壓 CAB
}
}
list.txt 列出來源檔案,呼叫 makecab /F list.txt,再從暫存目錄尋找產生的 .cab 移至目標路徑。expand "source.cab" "targetDir" -f:*,解析命令輸出取得解壓檔案清單。Process 啟動 cmd.exe,重導向標準輸入/輸出,隱藏視窗,設定 60 秒逾時。CabTemp,每次建構時重建確保乾淨。此類別提供簡潔的 out string errorInfo 錯誤回報模式,方便上層呼叫者處理失敗情況。