托管伺服器常需提供檔案上傳/下載功能替代 FTP。使用者上傳 .rar 封裝後,伺服器需自動解壓至指定目錄、可選刪除原壓縮檔,以利後續處理。
public void DecompressRAR(string rarPath, string destDir, bool deleteAfter)
{
string winRarExe = Server.MapPath(@"../EnterpriseCustom/WinRAR.exe"); // 需預先部署
if (!File.Exists(winRarExe))
throw new Exception("伺服器缺少 WinRAR.exe,請聯繫管理員!");
destDir = EnsureTrailingSlash(destDir);
try
{
Process p = new Process();
p.StartInfo.FileName = winRarExe;
// x=解壓 -inul=無訊息 -y=全選是 -o+=覆蓋
p.StartInfo.Arguments = $"x -inul -y -o+ \"{rarPath}\" \"{destDir}\"";
p.Start();
p.WaitForExit(); // 同步等待結束
}
catch (Exception ex)
{
throw new Exception("解壓失敗,請檢查寫入權限或檔案損毀:" + ex.Message);
}
if (deleteAfter) File.Delete(rarPath);
}
private string EnsureTrailingSlash(string path) =>
path.EndsWith("\\") ? path : path + "\\";
| 參數 | 含義 |
|---|---|
x | 解壓縮(保留目錄結構) |
-inul | 禁用所有訊息視窗,適合無人值守 |
-y | 所有提示預設「是」(覆蓋、繼續等) |
-o+ | 覆蓋既有檔案不提示 |
WinRAR.exe 放置於網站可存取路徑(如 EnterpriseCustom 目錄)。若不想依賴外部執行檔,可改用純 managed 庫 SharpCompress 或 SevenZipSharp,支援更多格式(zip/7z/gzip)且無需部署額外 exe。