工作项目中需要用到zip压缩解压缩文件,一开始看上了Ionic.Zip.dll这个类库,操作方便,写法简单

对应有个ziphelper类

using Ionic.Zip;public static class ZipHelper{public static void UnZip(string zipPath, string outPath){try{using (ZipFile zip = ZipFile.Read(zipPath)){foreach (ZipEntry entry in zip){entry.Extract(outPath, ExtractExistingFileAction.OverwriteSilently);}}}catch(Exception ex){File.WriteAllText(System.Web.HttpContext.Current.Server.MapPath("/1.txt"),ex.Message + "\r\n" + ex.StackTrace);}}/// <summary>/// 递归子目录时调用/// ZipHelper.Zip(files, path + model.CName + "/" + siteid + ".zip", path + model.CName + "/");/// ZipHelper.ZipDir( path + model.CName + "/" + siteid + ".zip", path + model.CName + "/", path + model.CName + "/");/// </summary>/// <param name="savefileName">要保存的文件名</param>/// <param name="childPath">要遍历的目录</param>/// <param name="startPath">压缩包起始目录结尾必须反斜杠</param>public static void ZipDir(string savefileName, string childPath, string startPath){DirectoryInfo di = new DirectoryInfo(childPath);if (di.GetDirectories().Length > 0) //有子目录{foreach (DirectoryInfo dirs in di.GetDirectories()){string[] n = Directory.GetFiles(dirs.FullName, "*");Zip(n, savefileName, startPath);ZipDir(savefileName, dirs.FullName, startPath);}}}/// <summary>/// 压缩zip/// </summary>/// <param name="fileToZips">文件路径集合</param>/// <param name="zipedFile">想要压成zip的文件名</param>/// <param name="fileDirStart">文件夹起始目录结尾必须反斜杠</param>public static void Zip(string[] fileToZips, string zipedFile,string fileDirStart){using (ZipFile zip = new ZipFile(zipedFile, Encoding.UTF8)){foreach (string fileToZip in fileToZips){ string fileName = fileToZip.Substring(fileToZip.LastIndexOf("\\", StringComparison.Ordinal) + 1);zip.AddFile(fileToZip, fileToZip.Replace(fileDirStart, "").Replace(fileName, ""));//zip.AddFile(fileToZip, fileToZip.Replace(fileDirStart, "").Replace(fileName, ""));//using (var fs = new FileStream(fileToZip, FileMode.Open, FileAccess.ReadWrite))//{//    var buffer = new byte[fs.Length];//    fs.Read(buffer, 0, buffer.Length);//    string fileName = fileToZip.Substring(fileToZip.LastIndexOf("\\", StringComparison.Ordinal) + 1);//    zip.AddEntry(fileName, buffer);//}}zip.Save();}}public static void ZipOneFile(string from, string zipedFile, string to){using (ZipFile zip = new ZipFile(zipedFile, Encoding.UTF8)){zip.AddFile(from, to);zip.Save();}}}

使用方法:

string path = Request.MapPath("/");
    string[] files = Directory.GetFiles(path, "*");
    ZipHelper.Zip(files, path + "1.zip", path);//压缩path下的所有文件
    ZipHelper.ZipDir(path + "1.zip", path, path);//递归压缩path下的文件夹里的文件
    ZipHelper.UnZip(Server.MapPath("/") + "lgs.zip", Server.MapPath("/"));//解压缩

正常情况下这个使用是不会有问题的,我一直在用,不过我遇到了一个变态问题,服务器端为了安全需求,禁用了File.Move方法,然后这个类库解压缩时采用了重命名方案,然后很尴尬的执行失败,困扰了我大半年时间,一直不知道原因,不过因为这个bug时隐时现,在 个别服务器上出现,所以一直没有解决,总算最近发现问题了。

于是我想干脆不用zip压缩了,直接调用服务器上的WinRar,这个问题显而易见,服务器如果没有安装,或者不给权限同样无法使用,我就遇到了,不过给个操作方法代码

public class WinRarHelper
{public WinRarHelper(){}static WinRarHelper(){//判断是否安装了WinRar.exeRegistryKey key = Registry.LocalMachine.OpenSubKey(@"SOFTWARE\Microsoft\Windows\CurrentVersion\App Paths\WinRAR.exe");_existSetupWinRar = !string.IsNullOrEmpty(key.GetValue(string.Empty).ToString());//获取WinRar.exe路径_winRarPath = key.GetValue(string.Empty).ToString();}static bool _existSetupWinRar;/// <summary>/// 获取是否安装了WinRar的标识/// </summary>public static bool ExistSetupWinRar{get { return _existSetupWinRar; }}static string _winRarPath;/// <summary>/// 获取WinRar.exe路径/// </summary>public static string WinRarPath{get { return _winRarPath; }}#region 压缩到.rar,这个方法针对目录压缩/// <summary>/// 压缩到.rar,这个方法针对目录压缩/// </summary>/// <param name="intputPath">输入目录</param>/// <param name="outputPath">输出目录</param>/// <param name="outputFileName">输出文件名</param>public static void CompressRar(string intputPath, string outputPath, string outputFileName){//rar 执行时的命令、参数string rarCmd;//启动进程的参数ProcessStartInfo processStartInfo = new ProcessStartInfo();//进程对象Process process = new Process();try{if (!ExistSetupWinRar){throw new ArgumentException("请确认服务器上已安装WinRar应用!");}//判断输入目录是否存在if (!Directory.Exists(intputPath)){throw new ArgumentException("指定的要压缩目录不存在!");}//命令参数  uxinxin修正参数压缩文件到当前目录,而不是从盘符开始rarCmd = " a " + outputFileName + " " + "./" + " -r";//rarCmd = " a " + outputFileName + " " + outputPath + " -r";//创建启动进程的参数//指定启动文件名processStartInfo.FileName = WinRarPath;//指定启动该文件时的命令、参数processStartInfo.Arguments = rarCmd;//指定启动窗口模式:隐藏processStartInfo.WindowStyle = ProcessWindowStyle.Hidden;//指定压缩后到达路径processStartInfo.WorkingDirectory = outputPath;//创建进程对象//指定进程对象启动信息对象process.StartInfo = processStartInfo;//启动进程process.Start();//指定进程自行退行为止process.WaitForExit();//Uxinxin增加的清理关闭,不知道是否有效process.Close();process.Dispose();}catch (Exception ex){throw ex;}finally{process.Close();process.Dispose();}}#endregion#region 解压.rar/// <summary>/// 解压.rar/// </summary>/// <param name="inputRarFileName">输入.rar</param>/// <param name="outputPath">输出目录</param>public static void UnCompressRar(string inputRarFileName, string outputPath){//rar 执行时的命令、参数string rarCmd;//启动进程的参数ProcessStartInfo processStartInfo = new ProcessStartInfo();//进程对象Process process = new Process();try{if (!ExistSetupWinRar){throw new ArgumentException("请确认服务器上已安装WinRar应用!");}//如果压缩到目标路径不存在if (!Directory.Exists(outputPath)){//创建压缩到目标路径Directory.CreateDirectory(outputPath);}rarCmd = "x " + inputRarFileName + " " + outputPath + " -y";processStartInfo.FileName = WinRarPath;processStartInfo.Arguments = rarCmd;processStartInfo.WindowStyle = ProcessWindowStyle.Hidden;processStartInfo.WorkingDirectory = outputPath;process.StartInfo = processStartInfo;process.Start();process.WaitForExit();process.Close();process.Dispose();}catch (Exception ex){throw ex;}finally{process.Close();process.Dispose();}}#endregion#region 将传入的文件列表压缩到指定的目录下/// <summary>/// 将传入的文件列表压缩到指定的目录下/// </summary>/// <param name="sourceFilesPaths">要压缩的文件路径列表</param>/// <param name="compressFileSavePath">压缩文件存放路径</param>/// <param name="compressFileName">压缩文件名(全名)</param>public static void CompressFilesToRar(List<string> sourceFilesPaths, string compressFileSavePath, string compressFileName){//rar 执行时的命令、参数string rarCmd;//启动进程的参数ProcessStartInfo processStartInfo = new ProcessStartInfo();//创建进程对象//进程对象Process process = new Process();try{if (!ExistSetupWinRar){throw new ArgumentException("Not setuping the winRar, you can Compress.make sure setuped winRar.");}//判断输入文件列表是否为空if (sourceFilesPaths == null || sourceFilesPaths.Count < 1){throw new ArgumentException("CompressRar'arge : sourceFilesPaths cannot be null.");}rarCmd = " a -ep1 -ap " + compressFileName;//-ep1 -ap表示压缩时不保留原有文件的路径,都压缩到压缩包中即可,调用winrar命令内容可以参考我转载的另一篇文章:教你如何在DOS(cmd)下使用WinRAR压缩文件foreach (object filePath in sourceFilesPaths){rarCmd += " " + filePath.ToString(); //每个文件路径要与其他的文件用空格隔开}//rarCmd += " -r";//创建启动进程的参数//指定启动文件名processStartInfo.FileName = WinRarPath;//指定启动该文件时的命令、参数processStartInfo.Arguments = rarCmd;//指定启动窗口模式:隐藏processStartInfo.WindowStyle = ProcessWindowStyle.Hidden;//指定压缩后到达路径processStartInfo.WorkingDirectory = compressFileSavePath;//指定进程对象启动信息对象process.StartInfo = processStartInfo;//启动进程process.Start();//指定进程自行退行为止process.WaitForExit();process.Close();process.Dispose();}catch (Exception ex){throw ex;}finally{process.Close();process.Dispose();}}#endregion
}

调用方法:

if (WinRarHelper.ExistSetupWinRar)
        {
            try
            {
                WinRarHelper.CompressRar(Server.MapPath("/"), Server.MapPath("/"), "1.zip");
                Response.Write("压缩完成!" + DateTime.Now);
            }
            catch (Win32Exception e1)
            {
                Response.Write(e1.Message + "<br>" + "服务器端禁止是我们网站使用WinRar应用执行!<br>");
            }
            catch (Exception e1)
            {
                Response.Write(e1.Message + "<br>" + e1.StackTrace);
            }

if (WinRarHelper.ExistSetupWinRar)
        {
            try
            {
                WinRarHelper.UnCompressRar(Server.MapPath("/") + "lgs.zip", Server.MapPath("/"));
                Response.Write("解压缩完成!" + DateTime.Now);
            }
            catch (Win32Exception e1)
            {
                Response.Write(e1.Message + "<br>" + "服务器端禁止是我们网站使用WinRar应用执行!<br>");

}
            catch (Exception e1)
            {
                Response.Write(e1.Message);
            }
        }

最后我找到了一个解压的时候不用重命名方法的,还好服务器对解压没限制

ICSharpCode.SharpZipLib.dll  用到这个文件

参考来自http://www.cnblogs.com/yuangang/p/5581391.html

具体我也不写了,就看参考网站吧,我也没改代码,不错,记录一下,花了我整整一天折腾这玩意儿!

【转】C#执行rar,zip文件压缩的几种方法及我遇到的坑总结相关推荐

  1. 7z001怎么解压在安卓手机上面_安卓zip文件压缩RAR解压手机下载-安卓zip文件压缩RAR解压v1.0最新版下载...

    安卓zip文件压缩RAR解压是一款非常好用的手机压缩解压缩神器,在安卓zip文件压缩RAR解压上我们可以看到很多的实用的功能,软件可以帮助我们更好的处理我们手机中的文件,感兴趣的朋友赶紧下载安卓zip ...

  2. cordova 安卓文件多选_安卓zip文件压缩RAR解压软件下载-安卓zip文件压缩RAR解压下载v3.0.4安卓版...

    安卓zip文件压缩RAR解压是一款非常好用的手机压缩解压缩神器,在安卓zip文件压缩RAR解压上我们可以看到很多的实用的功能,软件可以帮助我们更好的处理我们手机中的文件,感兴趣的朋友赶紧下载安卓zip ...

  3. ZIP文件压缩与解压缩

    ZIP4J解压优点 ZIP4J 是一个支持处理ZIP文件的开源库 支持创建,修改,添加,删除,解压 压缩文件 支持读/写密码保护 支持AES加密 128/256 支持标准ZIP加密 支持进度监视器 自 ...

  4. 解压 rar,zip 文件保存到本地

    提示:文章写完后,目录可以自动生成,如何生成可参考右边的帮助文档 文章目录 前言 一.导入依赖 二.功能代码 三.测试结果 解压前 解压后 总结 参考博客1 参考博客2 参考博客3(此方法未使用) 前 ...

  5. asp.net利用RAR实现文件压缩解压缩【月儿原创】

    asp.net利用RAR实现文件压缩解压缩 作者:清清月儿 主页:http://blog.csdn.net/21aspnet/           时间:2007.6.13 如果服务器上安装了RAR程 ...

  6. asp.net利用RAR实现文件压缩解压缩(转)

    如果服务器上安装了RAR程序,那么asp.net可以调用RAR实现文件压缩与解压缩. 不过要注意的是,由于Web程序不能直接调用客户端的程序(除非用ActiveX,ActiveX几乎被废弃),所以如果 ...

  7. java 操作Zip文件(压缩、解压、加密)

    java 操作Zip文件(压缩.解压.加密) 依赖:点击下载 package com.zxl.test;import net.lingala.zip4j.model.ZipParameters; im ...

  8. iOS Zip文件压缩

    iOS Zip文件压缩 //文件做压缩 拿到准备压缩的文件路径 拼装到数组中 使用的压缩类库 SSZipArchive//压缩文件路径 NSString *zippedPath; NSArray *p ...

  9. java对文件进行压缩的两种方法

    在工作中,我们或多或少都会接触到文件的压缩和解压,在window系统中,我们只需下载一个能对文件进行解压缩的应用即可,但如果让我们自己动手写对文件压缩的代码,顿时就头大了. 在java中,我们都知道输 ...

最新文章

  1. IBM WebSphere MQ 7.5基本用法
  2. C指针原理(46)-C应用技巧(1)
  3. Knative 化繁为简之道:应用部署与访问
  4. Amazon behavior question
  5. 七秘诀工作效率与薪水翻番
  6. ehd边缘直方图描述子 matlab,一种新的图像空间特征提取方法
  7. 第一章 简介和古典密码(粗略版) - 现代密码学导论 Introduction to Modern Cryptography
  8. EditText属性及一些常用用法
  9. javaweb mysql毕业生管理系统_javaweb高校毕业生就业管理系统, springmvc+mysql
  10. 毕业四年间,一壶漂泊,歌者默然(转帖)
  11. 吐槽一下程序员职场那些令人迷惑的行为
  12. android流量卡信息,Android 双卡获取当前使用流量在线卡的信息
  13. 项目管理模型总结---原型模型、迭代模型
  14. 微信支付API v3接口使用应用篇
  15. SpringSecurity-基于微服务的认证与权限访问
  16. 固定资产管理系统能给企业带来什么?
  17. Canal:部署Canal与Canal Admin
  18. Linux 内核clk 硬件相关层
  19. html页面无法显示生僻字,生僻字打不出来怎么办
  20. FineReport JS实现分页预览改变鼠标悬停所在的行列的背景色

热门文章

  1. Vagrant 构建 Linux 开发环境
  2. jQuery 简单案例
  3. bzoj 1024 [SCOI2009]生日快乐——模拟
  4. ASP.NET MVC5(一):ASP.NET MVC概览
  5. 使用jquery时一些小技巧的总结
  6. 根据select不同的选项实现相应input框添加项的显示
  7. 四叉树碰撞优化版,速度飞一样
  8. 避免頁面重復提交3/15
  9. 服务器重装后怎么装系统,服务器如何安装系统,小编教你如何安装
  10. java面向对象程序设计董小园_java面向对象程序设计(董小园版).doc