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

 更新时间:2021年9月22日 10:07  点击:1949

本文实例讲述了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
  }
} 

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

[!--infotagslink--]

相关文章

  • C#实现简单的登录界面

    我们在使用C#做项目的时候,基本上都需要制作登录界面,那么今天我们就来一步步看看,如果简单的实现登录界面呢,本文给出2个例子,由简入难,希望大家能够喜欢。...2020-06-25
  • 浅谈C# 字段和属性

    这篇文章主要介绍了C# 字段和属性的的相关资料,文中示例代码非常详细,供大家参考和学习,感兴趣的朋友可以了解下...2020-11-03
  • ASP.NET购物车实现过程详解

    这篇文章主要为大家详细介绍了ASP.NET购物车的实现过程,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下...2021-09-22
  • C#中截取字符串的的基本方法详解

    这篇文章主要介绍了C#中截取字符串的的基本方法,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧...2020-11-03
  • C#连接SQL数据库和查询数据功能的操作技巧

    本文给大家分享C#连接SQL数据库和查询数据功能的操作技巧,本文通过图文并茂的形式给大家介绍的非常详细,需要的朋友参考下吧...2021-05-17
  • C#实现简单的Http请求实例

    这篇文章主要介绍了C#实现简单的Http请求的方法,以实例形式较为详细的分析了C#实现Http请求的具体方法,需要的朋友可以参考下...2020-06-25
  • C#中new的几种用法详解

    本文主要介绍了C#中new的几种用法,具有很好的参考价值,下面跟着小编一起来看下吧...2020-06-25
  • 使用Visual Studio2019创建C#项目(窗体应用程序、控制台应用程序、Web应用程序)

    这篇文章主要介绍了使用Visual Studio2019创建C#项目(窗体应用程序、控制台应用程序、Web应用程序),小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧...2020-06-25
  • C#开发Windows窗体应用程序的简单操作步骤

    这篇文章主要介绍了C#开发Windows窗体应用程序的简单操作步骤,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧...2021-04-12
  • C#从数据库读取图片并保存的两种方法

    这篇文章主要介绍了C#从数据库读取图片并保存的方法,帮助大家更好的理解和使用c#,感兴趣的朋友可以了解下...2021-01-16
  • C#和JavaScript实现交互的方法

    最近做一个小项目不可避免的需要前端脚本与后台进行交互。由于是在asp.net中实现,故问题演化成asp.net中jiavascript与后台c#如何进行交互。...2020-06-25
  • 经典实例讲解C#递归算法

    这篇文章主要用实例讲解C#递归算法的概念以及用法,文中代码非常详细,帮助大家更好的参考和学习,感兴趣的朋友可以了解下...2020-06-25
  • C++调用C#的DLL程序实现方法

    本文通过例子,讲述了C++调用C#的DLL程序的方法,作出了以下总结,下面就让我们一起来学习吧。...2020-06-25
  • 轻松学习C#的基础入门

    轻松学习C#的基础入门,了解C#最基本的知识点,C#是一种简洁的,类型安全的一种完全面向对象的开发语言,是Microsoft专门基于.NET Framework平台开发的而量身定做的高级程序设计语言,需要的朋友可以参考下...2020-06-25
  • C#变量命名规则小结

    本文主要介绍了C#变量命名规则小结,文中介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下...2021-09-09
  • c#中(&&,||)与(&,|)的区别详解

    这篇文章主要介绍了c#中(&&,||)与(&,|)的区别详解,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧...2020-06-25
  • C#绘制曲线图的方法

    这篇文章主要介绍了C#绘制曲线图的方法,以完整实例形式较为详细的分析了C#进行曲线绘制的具体步骤与相关技巧,具有一定参考借鉴价值,需要的朋友可以参考下...2020-06-25
  • C# 中如何取绝对值函数

    本文主要介绍了C# 中取绝对值的函数。具有很好的参考价值。下面跟着小编一起来看下吧...2020-06-25
  • c#自带缓存使用方法 c#移除清理缓存

    这篇文章主要介绍了c#自带缓存使用方法,包括获取数据缓存、设置数据缓存、移除指定数据缓存等方法,需要的朋友可以参考下...2020-06-25
  • C#学习笔记- 随机函数Random()的用法详解

    下面小编就为大家带来一篇C#学习笔记- 随机函数Random()的用法详解。小编觉得挺不错的,现在就分享给大家,也给大家做个参考。一起跟随小编过来看看吧...2020-06-25