C#操作Rar(压缩、解压)

cncms

发表于2014-05-10 15:08:03

原理:C#在命令行调用winrar.exe进行压缩解压操作,本代码仅推荐桌面应用软件使用(WinForm),如果是Web程序,最好还是使用Zip/7z等格式。

因为Zip是开源压缩算法,有相关类库直接调用,而不用使用命令行调应用程序,在Web下面直接调exe一般会因为权限不够而无法执行!

 

首先直接看C#代码:

            pathExe = Application.StartupPath + @"\WinRAR.exe";  
            Process p = new Process();  
            p.StartInfo.FileName = pathExe;  
            p.StartInfo.Arguments = @"a -as -r -afzip -ed -hp123 -ibck -nul -m5 -mt5 d:\kldder d:\easyui";  
            p.StartInfo.CreateNoWindow = true;  
            p.StartInfo.RedirectStandardInput = true;  
            p.StartInfo.RedirectStandardError = false;  
            p.StartInfo.RedirectStandardOutput = true;  
            p.StartInfo.UseShellExecute = false;  
            p.StartInfo.ErrorDialog = false;  
            p.Start();  
            int idx = 1;  
            while (!p.HasExited)  
            {  
                idx++;  
                p.WaitForExit(500);  
                if (idx == 5)  
                {  
                    p.Kill();  
                }  
            }  
            p.Close();  
            p.Dispose();

 

可以直接将winrar.exe 拷贝到 根目录下运行,如果不需要弹窗只要加上参数 -ibck -inul 即可!

 

附:winrar参数说明:

<命令> -<开关1> -<开关N> <压缩文件 > <文件...> <@列表文件...> <解压路径\>
压缩 a a -as -ed -inul -afrar -df -ibck -m4 -mt3 -or -y -hp123 d:\aa d:\aa.txt
解压 x x -hp123 -ibck -inul -y -mt5 d:\aa.rar a:\
a d:\Info.zip D:\easyui
-af 指定格式 -afzip -afrar
-as 在当前添加的文件列表中不存在的被压缩文件,将会从压缩文件中删除
-df 压缩后删除源文件
-dr 删除到回收站
-ed 不添加空文件夹
-hp 添加密码 -jiniannet
-ibck 后台运行
-inul 禁止错误信息
-loff 压缩完成后 关闭电源
-m0 存储 添加文件到压缩文件但是不压缩
-m1 最快 最快速的方法 ( 最低的压缩比)
-m2 快速 快速压缩方法
-m3 标准 标准 (默认 ) 压缩方法
-m4 较好 较好的压缩方法 (较高的压缩比)
-m5 最优 最优的压缩方法 (最高压缩比但是速度也最慢)
-mtN 线程 -mt5 1~32
-or 自动重命名文件
-r 连同子文件
-z 压缩后测试文件
-y 所有弹窗选择"是"

 

本文原文地址:http://tech.cncms.com/web/aspnet/98360.html