解壓 RAR,使用 unrar.dll C#

來源:互聯網
上載者:User
解壓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上才能執行哦)

 

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.