解壓RAR,使用 unrar.dll
比較常看到的解法,是用 process 調用 winrar 來解壓縮,但伺服器不一定有購買 winrar,調用 process 也要 iis 設定的internet 帳戶有足夠的許可權才行吧? 而另一種解法,是使用 unrar.dll 。
下載unrar 解開後,裡面有包括c#的各語言範例,看了 license.txt,應該是可以用在商業行為吧。
「may be used in any software to handle RAR archives without limitations free of charge」
我在 web site 專案試著使用,中文檔名也可以正確解開。但有點要注意,unrar.dll不是原生的.net dll, 而是用c++寫的, 他提供Unrar.cs是用c# 封裝一層用 DllImport呼叫其功能,因此專案裡是不用加入參考,直接copy 放到bin 目錄就可以了,另外也不行在開發環境的web server運作(會讀不到dll),放在iis上就可以了。
用起來真的很簡單,程式碼大概像這樣
using System;
using System.IO;
using Schematrix;
public partial class _Default : System.Web.UI.Page {
protected void Page_Load(object sender, EventArgs e) {
string file = Server.MapPath("~/App_Data/圖片.rar");
string targetPath = Server.MapPath("~/App_Data/");
DecompressRar(file, targetPath, false);
}
public void DecompressRar(string rarArchive, string destinationPath, bool CreateDir) {
if (File.Exists(rarArchive)) {
Unrar unrar = new Unrar(rarArchive);
unrar.Open(Unrar.OpenMode.Extract);
unrar.DestinationPath = destinationPath;
while (unrar.ReadHeader()) {
if (unrar.CurrentFile.IsDirectory) {
unrar.Skip();
} else {
if (CreateDir) {
unrar.Extract();
} else {
unrar.Extract(destinationPath + Path.GetFileName(unrar.CurrentFile.FileName));
}
}
}
unrar.Close();
}
}
}
下載整個範例(要在IIS上才能執行哦)