解压 RAR,使用 unrar.dll C#

解压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上才能执行哦)

 

posted @ 2010-01-08 15:29  Kevin.Cheung  阅读(3822)  评论(1编辑  收藏  举报