ASP. NET file compression and decompression class (C)

  • 2021-08-03 10:01:24
  • OfStack

In this paper, the method of extracting files by asp. net C # is described. It is necessary to refer to one ICSharpCode. SharpZipLib. dll for your reference, as follows:


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>  ///  Author: From Grid <br>  ///  Modifier :sunkaixaun
  ///  Compress and unzip files  
  /// </summary> 
  public class ZipClass
  {
    /// <summary> 
    ///  All file cache  
    /// </summary> 
    List<string> files = new List<string>();
 
    /// <summary> 
    ///  All empty directory caches  
    /// </summary> 
    List<string> paths = new List<string>();

    /// <summary> 
    ///  Compress a single file according to the file address 
    /// </summary> 
    /// <param name="fileToZip"> File to be compressed </param> 
    /// <param name="zipedFile"> Full name of compressed file </param> 
    /// <param name="compressionLevel"> Degree of compression, range 0-9 The larger the value, the higher the compression program </param> 
    /// <param name="blockSize"> Block size </param> 
    public void ZipFile(string fileToZip, string zipedFile, int compressionLevel, int blockSize)
    {
      if (!System.IO.File.Exists(fileToZip))// If the file is not found, an error is reported  
      {
        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> 
    ///  Compressed directory (including subdirectories and all files)  
    /// </summary> 
    /// <param name="rootPath"> Root directory to compress </param> 
    /// <param name="destinationPath"> Save path </param> 
    /// <param name="compressLevel"> Degree of compression, range 0-9 The larger the value, the higher the compression program </param> 
    public void ZipFileFromDirectory(string rootPath, string destinationPath, int compressLevel)

    {

      GetAllDirectories(rootPath);
      /* while (rootPath.LastIndexOf("\\") + 1 == rootPath.Length)// Check whether the path is used with "\" End  

      { 

       rootPath = rootPath.Substring(0, rootPath.Length - 1);// If yes, remove the last "\" 

      } 
      */

      //string rootMark = rootPath.Substring(0, rootPath.LastIndexOf("\\") + 1);// The position of the current path is obtained for converting the compressed content into a relative path during compression.  
      string rootMark = rootPath + "\\";// The position of the current path is obtained for converting the compressed content into a relative path during compression.  
      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);// Open zip 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> 
    ///  Multi-file package download 
    /// </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();// With this name formatter, you can use the file name inside to 1 Some treatment. By default, it is automatically set in the zip Create the relevant folder in. 

        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> 
    ///  Get all files and folders in the directory and store them in files And paths 
    /// </summary> 
    /// <param name="rootPath"> Root directory </param> 
    private void GetAllDirectories(string rootPath)

    {

      string[] subPaths = Directory.GetDirectories(rootPath);// Get all subdirectories  

      foreach (string path in subPaths)

      {

        GetAllDirectories(path);// To each 1 The one-word directory does the same thing as the root directory: find the subdirectory and store the file name of the current directory in List 

      }

      string[] files = Directory.GetFiles(rootPath);

      foreach (string file in files)

      {
        this.files.Add(file);// Save the full names of all files in the current directory to a file List 
      }
      if (subPaths.Length == files.Length && files.Length == 0)// If it is an empty directory  
      {
        this.paths.Add(rootPath);// Record an empty directory  

      }

    }
    /// <summary> 
    ///  Extract a file ( The zip file contains subdirectories ) 
    /// </summary> 
    /// <param name="zipfilepath"> The path of the file to be unzipped </param> 
    /// <param name="unzippath"> Extract to specified directory </param> 
    /// <returns> File list after extraction </returns> 
    public List<string> UnZip(string zipfilepath, string unzippath)

    {
      // Extracted list of files  

      List<string> unzipFiles = new List<string>();
      // Check whether the output directory is marked with " \\ "End  

      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);

 

        // Generate unzipped directory "When users unzip to the root directory of hard disk, they do not need to create"  

        if (!string.IsNullOrEmpty(directoryName))

        {

          Directory.CreateDirectory(directoryName);
        }
        if (fileName != String.Empty)

        {
          // If the compressed size of the file is 0 Then the file is empty , So there is no need to read and write  

          if (theEntry.CompressedSize == 0)

            break;

          // Unzip the file to the specified directory  

          directoryName = Path.GetDirectoryName(unzippath + theEntry.Name);

          // Create the following directories and subdirectories  

          Directory.CreateDirectory(directoryName);
         // Record exported files  

          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  Member 

    public string TransformDirectory(string name)
    {
      return null;
    }
    public string TransformFile(string name)
    {
      return Path.GetFileName(name);
    }
    #endregion
  }
} 

Related articles: