C # zip compressed files

Source: Internet
Author: User

Sharpziplib file/folder Compression

1. zipfile

The zipfile class is used to select a file or folder for compression to generate a compressed package.

Common attributes:

Attribute Description
Count Number of files (note that this is available only after comitupdat)
Password Compressed package Password
Size Space occupied by the compressed package
Name The name of the compressed package. The default output is the file path.
Zipentry Files in the compressed package are accessed through the index []

The common method is as follows:

Method Description
Add Add the file to be compressed
Adddirectory Add a folder (files in the folder will not be compressed)
Delete Delete a file or folder
Beginupdate Start to modify the compressed package
Commitupdate Submit changes
Setcomment Add Comment

Example 1 (create a compressed file ):

Using (zipfile zip = zipfile.Create(@ "D: \ test.zip") {zip. beginupdate (); zip. setcomment ("this is my compressed package"); zip. add (@ "D: \ 1.txt"); // Add a file zip. adddirectory (@ "D: \ 2"); // Add a folder (this method does not compress the files in the folder) zip. add (@ "D: \ 2 \ 2.txt"); // Add the file zip in the folder. commitupdate ();}

The compressed package generated in this way contains subfolders, and subfolders also contain subfolders.

Note the following:

  

Example 2: modify a compressed package

  using (ZipFile zip = new ZipFile(@"D:\test.zip"))      {          zip.BeginUpdate();          zip.Add(@"D:\2.txt");          zip.CommitUpdate();      }

Pay attention to the differences between this example and the above. The above is the zipfile object created by the create method, which is directly read here. Therefore, if there is a file in the compressed package, it will not change the original compressed file, but will add. This is equivalent to the modification of the compressed package, and the above is the creation of the compressed package.

Example 3: read the files in the compressed package:

  using (ZipFile zip = new ZipFile(@"D:\test.zip"))      {          foreach (ZipEntry z in zip)          {              Console.WriteLine(z);          }          ZipEntry z1 = zip[0];          Console.WriteLine(z1.Name);     }
Ii. fastzip

This class has two methods:

Method Description
Createzip Compressed directory
Extractzip Decompress directory

  

1. fastzip is used to quickly compress directories, for example:

// Quickly compress the directory, including all files in the directory (New fastzip ()). createzip (@ "D: \ test.zip", @ "D: \ test \", true ,"");

This is recursive compression. But the limitation is that only folders can be compressed.

Otherwise, the following error is reported:

  

2. decompress the directory quickly

// Quickly decompress (New fastzip (). extractzip (@ "D: \ test.zip", @ "D: \ decompress directory \","");

 

3. zipoutputstream and zipentry
  • Zipoutputstream: equivalent to a compressed package;
  • Zipentry: it is equivalent to a file in the compressed package;

The above two classes are the primary class of sharpziplib, and the most playable class is the two.

Common attributes of zipoutputstream:

Attribute Description
Isfinished Indicates whether zipoutputstream has ended.

Common zipoutputstream methods:

Method Description
Closeentry Close the portal. You are not allowed to operate zipoutputstream after it is closed.
Finish End write
Getlevel Read compression level
Putnextentry Write a zipentry to zipoutputstream.
Setcomment Comments of the compressed package
Setlevel Set the compression level. The higher the level, the smaller the file size.
Write Write File Content

Example of using zipoutputstream to create a compressed package and write a file to it:

Static void main (string [] ARGs) {using (zipoutputstream S = new zipoutputstream (file. create (@ "D: \ 123.zip") {S. setlevel (6); // set the compression level. The higher the level, the more obvious the compression effect, but the more using (filestream FS = file. openread (@ "D: \ 1.txt") {byte [] buffer = new byte [4*1024]; // buffer, zipentry entry = new zipentry (path. getfilename (@ "RENAME .txt"); // create the file entry in the compressed package. datetime = datetime. now; // File Creation Time S. putnextentry (entry); // write the file to the compressed package int sourcebytes; do {sourcebytes = FS. read (buffer, 0, buffer. length); // read the file content (read 4 m once, write 4 m) s. write (buffer, 0, sourcebytes); // write the file content into the compressed file} while (sourcebytes> 0);} s. closeentry ();} console. readkey ();}

In the preceding example, only files can be compressed. To Compress folders, you must use recursive methods to compress subdirectories and compress files in subdirectories.

Example 2: folder compression to keep the original folder architecture:

Class program {static void main (string [] ARGs) {string source = @ "D: \ test"; string tartgetfile = @ "D: \ test.zip"; directory. createdirectory (path. getdirectoryname (tartgetfile); Using (zipoutputstream S = new zipoutputstream (file. create (tartgetfile) {S. setlevel (6); compress (source, S); S. finish (); S. close ();} console. readkey ();} /// <summary> /// compression // </Summary> /// <Param name = "Source"> source directory </param> /// <Param name = "S"> zipoutputstream object </param> Public static void compress (string source, zipoutputstream s) {string [] filenames = directory. getfilesystementries (source); foreach (string file in filenames) {If (directory. exists (File) {compress (file, S); // recursive compression subfolders} else {using (filestream FS = file. openread (File) {byte [] buffer = new byte [4*1024]; zipentry entry = new zipentry (file. replace (path. getpathroot (file), ""); // remove the drive letter here, for example, D: \ 123 \ 1.txt remove D: entry. datetime = datetime. now; S. putnextentry (entry); int sourcebytes; do {sourcebytes = FS. read (buffer, 0, buffer. length); S. write (buffer, 0, sourcebytes);} while (sourcebytes> 0 );}}}}}

Attached decompression method:

/// <Summary> /// extract /// </Summary> /// <Param name = "sourcefile"> source file </param> /// <Param name = "targetpath"> target path </param> Public bool decompress (string sourcefile, string targetpath) {If (! File. exists (sourcefile) {Throw new filenotfoundexception (string. Format ("File '{0}'", sourcefile) not found);} If (! Directory. exists (targetpath) {directory. createdirectory (targetpath);} using (zipinputstream S = new zipinputstream (file. openread (sourcefile) {zipentry theentry; while (theentry = S. getnextentry ())! = NULL) {string directorname = path. combine (targetpath, path. getdirectoryname (theentry. name); string filename = path. combine (directorname, path. getfilename (theentry. name); // create the directory if (directorname. length> 0) {directory. createdirectory (directorname);} If (filename! = String. empty) {using (filestream streamwriter = file. create (filename) {int size = 4096; byte [] DATA = new byte [4*1024]; while (true) {size = S. read (data, 0, Data. length); If (size> 0) {streamwriter. write (data, 0, size) ;}else break ;}}}return true ;}

Zipentry has nothing to say. It has some attributes. It indicates that it is rarely used.

From: http://www.cnblogs.com/kissdodog/p/3525295.html

C # zip compressed files

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.