asp.net file compression decompression class (C #) _ Practical Skills

Source: Internet
Author: User

This article describes the ASP.net C # implementation of the decompression file, you need to refer to a ICSharpCode.SharpZipLib.dll for your reference, specifically 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>///modified person: Sunkaixaun///Compression Reconciliation  
    Press file///</summary> public class Zipclass {///<summary>///all file caches///</summary>
 
    list<string> files = new list<string> ();

    <summary>///All empty directory cache///</summary> list<string> paths = new list<string> (); <summary>///Compressed individual files according to file address///</summary>///<param name= "Filetozip" > Files to compress </ param>///<param name= "Zipedfile" > Compressed file Full name </param>///<param name= "CompressionLevel" > Degree of compression  , Range 0-9, the larger the number, the higher the compression program </param>///<param name= "blockSize" > chunking 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, the error {throw new FileNotFoundException ("The specified file" + F Iletozip + "could not to 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, b Uffer.
          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 to Compress Directory </param>///<param name= "DestinationPath" > Save Paths </param>///<param name= "Compresslevel" &G t; compression level, range 0-9, the larger the number, 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 ends with "\" {RootPath = Rootpath.substrin G (0, rootpath.length-1);//If yes then remove the end of "\"} * * *//string Rootmark = rootpath.substring (0, Rootpath.las 
      Tindexof ("\") + 1)//Gets the position of the current path to convert the compressed content into a relative path for compression. 
      String Rootmark = RootPath + "\ \";//Get the position of the current path to convert the compressed content to a relative path for compression. Crc32 CRC = New CRC32 ();
      Zipoutputstream outputstream = new Zipoutputstream (File.create (DestinationPath)); Outputstream.setlevel (Compresslevel); 0-store 9-means Best Compression foreach (string file in files) {FileStream Filestrea
        m = file.openread (file);//Open compressed files 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 being stored in the header 
        If it is isn't 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 St 
        Ore//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, St
      Ring 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 ();//Through this name formatter, you can do some processing of the file name inside.

        By default, the relevant folder is automatically created in the zip based on the path to the file. 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>///access to all files and folders in the directory, respectively, into files and paths///</summary>///<param name= "rootpa Th "> root directory </param> private void GetAllDirectories (string rootpath) {string[] subpaths = directory. GetDirectories (RootPath);//Get All subdirectories foreach (string path in subpaths) {getalldirectories (path);

      Each word directory does the same thing as the root directory: Locate the subdirectory and store the current directory's file name in list} string[] files = directory.getfiles (RootPath); foreach (string file in files) {this.files.Add (file);//Save all the file names in the current directory to files LiST} if (subpaths.length = files. Length && files. Length = = 0)//If empty directory {THIS.PATHS.ADD (rootpath);//Log Empty Directory}}///<summary>///solution Compressed files (containing subdirectories in compressed files)///</summary>///<param name= "Zipfilepath" > the file path to be uncompressed </param>///<p Aram Name= "Unzippath" > uncompressed to specified directory </param>///<returns> uncompressed files list </returns> public List<strin G> UnZip (String zipfilepath, String unzippath) {//extracted file list list<string> unzipfiles = new Lis
      T<string> (); Checks whether the output directory ends with "\" 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 extract Directory "when the user extracts to the hard disk root directory, you do not need to create an if (!string).
        IsNullOrEmpty (directoryname)) {directory.createdirectory (directoryname); } if (filename!= string.empty) {//If the file has a compressed size of 0 Then the file is empty, so there is no need to read write to the IF (theentr

          Y.compressedsize = = 0) break;

          Unzip the file to the specified directory directoryname = path.getdirectoryname (Unzippath + theentry.name);
         Create the following directory and subdirectory Directory.CreateDirectory (directoryname);
         Record the exported file 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 P
    Ublic string Transformdirectory (string name) {return null;
    public string TransformFile (string name) {return path.getfilename (name); 
 } #endregion}}

The above is the entire content of this article, I hope to help you learn, but also hope that we support the cloud habitat community.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.