欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

ASP.NET 文件压缩解压类(C#)

程序员文章站 2023-11-27 09:25:22
本文实例讲述了asp.net c#实现解压缩文件的方法,需要引用一个icsharpcode.sharpziplib.dll,供大家参考,具体如下: using...

本文实例讲述了asp.net c#实现解压缩文件的方法,需要引用一个icsharpcode.sharpziplib.dll,供大家参考,具体如下:

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
{
  /// <summary> <br>  /// 作者:来自网格<br>  /// 修改人:sunkaixaun
  /// 压缩和解压文件 
  /// </summary> 
  public class zipclass
  {
    /// <summary> 
    /// 所有文件缓存 
    /// </summary> 
    list<string> files = new list<string>();
 
    /// <summary> 
    /// 所有空目录缓存 
    /// </summary> 
    list<string> paths = new list<string>();

    /// <summary> 
    /// 压缩单个文件根据文件地址
    /// </summary> 
    /// <param name="filetozip">要压缩的文件</param> 
    /// <param name="zipedfile">压缩后的文件全名</param> 
    /// <param name="compressionlevel">压缩程度,范围0-9,数值越大,压缩程序越高</param> 
    /// <param name="blocksize">分块大小</param> 
    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();

    }

    /// <summary> 
    /// 压缩目录(包括子目录及所有文件) 
    /// </summary> 
    /// <param name="rootpath">要压缩的根目录</param> 
    /// <param name="destinationpath">保存路径</param> 
    /// <param name="compresslevel">压缩程度,范围0-9,数值越大,压缩程序越高</param> 
    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();

    }
    /// <summary> 
    /// 多文件打包下载
    /// </summary> 
    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();

    }
    /// <summary> 
    /// 取得目录下所有文件及文件夹,分别存入files及paths 
    /// </summary> 
    /// <param name="rootpath">根目录</param> 
    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);//记录空目录 

      }

    }
    /// <summary> 
    /// 解压缩文件(压缩文件中含有子目录) 
    /// </summary> 
    /// <param name="zipfilepath">待解压缩的文件路径</param> 
    /// <param name="unzippath">解压缩到指定目录</param> 
    /// <returns>解压后的文件列表</returns> 
    public list<string> unzip(string zipfilepath, string unzippath)

    {
      //解压出来的文件列表 

      list<string> unzipfiles = new list<string>();
      //检查输出目录是否以“\\”结尾 

      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
  }
} 

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。