ASP.NET如何实现文件压缩解压类
创始人
2024-11-28 10:42:27
0次

具体如下:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using ICSharpCode.SharpZipLib.Zip;
using System.IO;
using ICSharpCode.SharpZipLib.Checksums;
using System.Web;
namespace Mvc51Hiring.Common.Tool
{
  ///  
  /// 作者:来自网格
  /// 修改人:sunkaixaun   /// 压缩和解压文件    /// 
    public class ZipClass   {     ///       /// 所有文件缓存      ///       List files = new List();       ///       /// 所有空目录缓存      ///       List paths = new List();     ///       /// 压缩单个文件根据文件地址     ///       /// 要压缩的文件      /// 压缩后的文件全名      /// 压缩程度,范围0-9,数值越大,压缩程序越高      /// 分块大小      public void ZipFile(string fileToZip, string zipedFile, int compressionLevel, int blockSize)     {       if (!System.IO.File.Exists(fileToZip))//如果文件没有找到,则报错        {         throw new FileNotFoundException("The specified file " + fileToZip + " could not be found. Zipping aborderd");       }       FileStream streamToZip = new FileStream(fileToZip, FileMode.Open, FileAccess.Read);       FileStream zipFile = File.Create(zipedFile);       ZipOutputStream zipStream = new ZipOutputStream(zipFile);       ZipEntry zipEntry = new ZipEntry(fileToZip);       zipStream.PutNextEntry(zipEntry);       zipStream.SetLevel(compressionLevel);       byte[] buffer = new byte[blockSize];       int size = streamToZip.Read(buffer, 0, buffer.Length);       zipStream.Write(buffer, 0, size);       try       {         while (size < streamToZip.Length)         {           int sizeRead = streamToZip.Read(buffer, 0, buffer.Length);           zipStream.Write(buffer, 0, sizeRead);           size += sizeRead;         }       }       catch (Exception ex)       {         GC.Collect();         throw ex;       }       zipStream.Finish();       zipStream.Close();       streamToZip.Close();       GC.Collect();     }     ///       /// 压缩目录(包括子目录及所有文件)      ///       /// 要压缩的根目录      /// 保存路径      /// 压缩程度,范围0-9,数值越大,压缩程序越高      public void ZipFileFromDirectory(string rootPath, string destinationPath, int compressLevel)     {       GetAllDirectories(rootPath);       /* while (rootPath.LastIndexOf("\\") + 1 == rootPath.Length)//检查路径是否以"\"结尾        {         rootPath = rootPath.Substring(0, rootPath.Length - 1);//如果是则去掉末尾的"\"        }        */       //string rootMark = rootPath.Substring(0, rootPath.LastIndexOf("\\") + 1);//得到当前路径的位置,以备压缩时将所压缩内容转变成相对路径。        string rootMark = rootPath + "\\";//得到当前路径的位置,以备压缩时将所压缩内容转变成相对路径。        Crc32 crc = new Crc32();       ZipOutputStream outPutStream = new ZipOutputStream(File.Create(destinationPath));       outPutStream.SetLevel(compressLevel); // 0 - store only to 9 - means best compression        foreach (string file in files)       {         FileStream fileStream = File.OpenRead(file);//打开压缩文件          byte[] buffer = new byte[fileStream.Length];         fileStream.Read(buffer, 0, buffer.Length);         ZipEntry entry = new ZipEntry(file.Replace(rootMark, string.Empty));         entry.DateTime = DateTime.Now;         // set Size and the crc, because the information          // about the size and crc should be stored in the header          // if it is not set it is automatically written in the footer.          // (in this case size == crc == -1 in the header)          // Some ZIP programs have problems with zip files that don't store          // the size and crc in the header.          entry.Size = fileStream.Length;         fileStream.Close();         crc.Reset();         crc.Update(buffer);         entry.Crc = crc.Value;         outPutStream.PutNextEntry(entry);         outPutStream.Write(buffer, 0, buffer.Length);       }    this.files.Clear();     foreach (string emptyPath in paths)       {         ZipEntry entry = new ZipEntry(emptyPath.Replace(rootMark, string.Empty) + "/");         outPutStream.PutNextEntry(entry);       }       this.paths.Clear();       outPutStream.Finish();       outPutStream.Close();       GC.Collect();     }     ///       /// 多文件打包下载     ///       public void DwonloadZip(string[] filePathList, string zipName)     {       MemoryStream ms = new MemoryStream();       byte[] buffer = null;       var context = HttpContext.Current;       using (ICSharpCode.SharpZipLib.Zip.ZipFile file = ICSharpCode.SharpZipLib.Zip.ZipFile.Create(ms))       {         file.BeginUpdate();         file.NameTransform = new MyNameTransfom();//通过这个名称格式化器,可以将里面的文件名进行一些处理。默认情况下,会自动根据文件的路径在zip中创建有关的文件夹。         foreach (var it in filePathList)         {           file.Add(context.Server.MapPath(it));         }         file.CommitUpdate();         buffer = new byte[ms.Length];         ms.Position = 0;         ms.Read(buffer, 0, buffer.Length);       }       context.Response.AddHeader("content-disposition", "attachment;filename=" + zipName);       context.Response.BinaryWrite(buffer);       context.Response.Flush();       context.Response.End();     }     ///       /// 取得目录下所有文件及文件夹,分别存入files及paths      ///       /// 根目录      private void GetAllDirectories(string rootPath)     {       string[] subPaths = Directory.GetDirectories(rootPath);//得到所有子目录        foreach (string path in subPaths)       {         GetAllDirectories(path);//对每一个字目录做与根目录相同的操作:即找到子目录并将当前目录的文件名存入List        }       string[] files = Directory.GetFiles(rootPath);       foreach (string file in files)       {         this.files.Add(file);//将当前目录中的所有文件全名存入文件List        }       if (subPaths.Length == files.Length && files.Length == 0)//如果是空目录        {         this.paths.Add(rootPath);//记录空目录        }     }     ///       /// 解压缩文件(压缩文件中含有子目录)      ///       /// 待解压缩的文件路径      /// 解压缩到指定目录      /// 解压后的文件列表      public List UnZip(string zipfilepath, string unzippath)     {       //解压出来的文件列表        List unzipFiles = new List();       //检查输出目录是否以“\\”结尾        if (unzippath.EndsWith("\\") == false || unzippath.EndsWith(":\\") == false)       {         unzippath += "\\";       }       ZipInputStream s = new ZipInputStream(File.OpenRead(zipfilepath));       ZipEntry theEntry;       while ((theEntry = s.GetNextEntry()) != null)       {         string directoryName = Path.GetDirectoryName(unzippath);         string fileName = Path.GetFileName(theEntry.Name);           //生成解压目录【用户解压到硬盘根目录时,不需要创建】          if (!string.IsNullOrEmpty(directoryName))         {           Directory.CreateDirectory(directoryName);         }         if (fileName != String.Empty)         {           //如果文件的压缩后大小为0那么说明这个文件是空的,因此不需要进行读出写入            if (theEntry.CompressedSize == 0)             break;           //解压文件到指定的目录            directoryName = Path.GetDirectoryName(unzippath + theEntry.Name);           //建立下面的目录和子目录            Directory.CreateDirectory(directoryName);          //记录导出的文件            unzipFiles.Add(unzippath + theEntry.Name);          FileStream streamWriter = File.Create(unzippath + theEntry.Name);           int size = 2048;           byte[] data = new byte[2048];           while (true)           {             size = s.Read(data, 0, data.Length);             if (size > 0)             {               streamWriter.Write(data, 0, size);             }             else             {               break;             }           }           streamWriter.Close();         }       }       s.Close();       GC.Collect();       return unzipFiles;     }   }   public class MyNameTransfom : ICSharpCode.SharpZipLib.Core.INameTransform   {     #region INameTransform 成员     public string TransformDirectory(string name)     {       return null;     }     public string TransformFile(string name)     {       return Path.GetFileName(name);     }     #endregion   } }

相关内容

热门资讯

空调连续工作多久需要停机休息 空调连续工作的时间取决于多个因素,包括空调的型号、功率、使用环境和维护情况等。一般来说,空调可以连续...
空调哪个符号是除湿的 空调除湿功能通常用一个水滴形状的符号表示。不同品牌和型号的空调遥控器可能会有所差异,但一般来说,除湿...
格力空调多长时间加一次氟利昂 1、一般情况下,空调对氟利昂的使用量是非常小的,所以在空调使用了四年左右的时候再考虑加也没问题。2、...
空调用多长时间需要加氟一次 一般情况下是五年。当出现以下这几种情况时,空调才需要加氟。1、空调的室内机和室外机各有两个接口,当接...
格调生活·C标思享荟:卡萨帝在... 9月12日的郑州龙湖金融岛,夜风轻拂,灯光璀璨。“C标时刻共传奇——卡萨帝思享荟暨20周年品牌盛典郑...
品牌价值破千亿、高端份额持续领... 9月12日,“C标时刻共传奇——卡萨帝思享荟暨20周年品牌盛典郑州站”在郑州龙湖金融岛举办。2026...
空调主板坏了修800还是换新的 空调主板坏了是修还是换新,需要考虑多个因素,以下是一些建议:1. 维修成本:如果维修费用较低,比如 ...
空调开多久需要休息多长时间 问题:空调开多久需要休息多长时间回答:1、在使用空调的过程中,一般空调开7~8个小时左右需要休息2~...
中央空调多长时间清洗一次 1、一般空调开机前清洗一次即可,空调开机中间时段再清洗一次,空调关机时清洗一次,这样比较合理。2、空...
中央空调氟利昂多久加一次 看空调制热和制冷程度,很多人的观点认为氟利昂必须一年放一次,其实这个观点是错误的,理解上面有点偏差,...