[Downloadable] zip compression and decompression help class encapsulation in C #

Source: Internet
Author: User

C # zip compression and decompression help class Encapsulation

 

After a classmate asked this question, he looked at the encapsulation of other garden friends in the garden, which was fragmented and not convenient to call. So I encapsulated a zip decompressed class. Later, I want to sort it out for fear that I forgot it. The compressed classes are also encapsulated.

C # is compressed and decompressed, which is encapsulated by a third-party class library. ICSharpCode. SharpZipLib. dll class library, which can be downloaded from your official website. Compression is mainly performed using stream compression.

 

Compress files and folders. File compression is simple. You can read the files to be compressed into the memory in the stream mode and put them in the compressed stream. You can. Folder is a little troublesome. Because you need to extract the folder to be compressed and keep the hierarchical structure of the folder file. So my implementation method is to recursively traverse the files in the folder. Computation the relative position to the compressed stream.

The Code is as follows:

/// <Summary> /// compressed file or folder /// </summary> /// <param name = "_ depositPath"> the compressed file storage path is as follows: C: \ windows \ abc.zip </param> // <returns> </returns> public bool CompressionZip (string _ depositPath) {bool result = true; FileStream fs = null; try {ZipOutputStream ComStream = new ZipOutputStream (File. create (_ depositPath); ComStream. setLevel (9); // compression level foreach (string path in AbsolutePaths) {// if it is a directory if (Direct Ory. exists (path) {ZipFloder (path, ComStream, path);} else if (File. exists (path) // if it is a File {fs = File. openRead (path); byte [] bts = new byte [fs. length]; fs. read (bts, 0, bts. length); ZipEntry ze = new ZipEntry (new FileInfo (path ). name); ComStream. putNextEntry (ze); // provides a container ComStream for the compressed file stream. write (bts, 0, bts. length); // write byte} ComStream. finish (); // end the compressed ComStream. close ();} catch (Exception ex) {if (Fs! = Null) {fs. close ();} errorMsg = ex. message; result = false;} return result;} // compressed folder private void ZipFloder (string _ OfloderPath, ZipOutputStream zos, string _ floderPath) {foreach (FileSystemInfo item in new DirectoryInfo (_ floderPath ). getFileSystemInfos () {if (Directory. exists (item. fullName) {ZipFloder (_ OfloderPath, zos, item. fullName);} else if (File. exists (item. fullName) // if the file is {DirectoryInfo ODir = new DirectoryInfo (_ OfloderPath); string fullName2 = new FileInfo (item. fullName ). fullName; string path = ODir. name + fullName2.Substring (ODir. fullName. length, fullName2.Length-ODir. fullName. length); // obtain the relative directory FileStream fs = File. openRead (fullName2); byte [] bts = new byte [fs. length]; fs. read (bts, 0, bts. length); ZipEntry ze = new ZipEntry (path); zos. putNextEntry (ze); // provides a container zos for the compressed file stream. write (bts, 0, bts. length); // write bytes }}}

 

It is much easier to decompress the package. Files are extracted, folders are traversed, and files are extracted. The decompressed file contains the hierarchical relationship between it and the folder.

 

/// <Summary> /// extract /// </summary> /// <param name = "_ depositPath"> compressed file path </param> /// <param name = "_ floderPath"> decompressed path </param> // <returns> </returns> public bool DeCompressionZip (string _ depositPath, string _ floderPath) {bool result = true; FileStream fs = null; try {ZipInputStream InpStream = new ZipInputStream (File. openRead (_ depositPath); ZipEntry ze = InpStream. getNextEntry (); // obtain the Di of each file in the compressed file Rectory. CreateDirectory (_ floderPath); // create the decompressed folder while (ze! = Null) // if ze is decompressed, It is null {if (ze. IsFile) // compressed zipINputStream stores all files. The file name with a folder is Folder \ file name {string [] strs = ze. name. split ('\'); // if the file name contains '\', the folder if (strs. length> 1) {// a two-tier loop is used to create a folder for (int I = 0; I <strs. length-1; I ++) {string floderPath = _ floderPath; for (int j = 0; j <I; j ++) {floderPath = floderPath + "\" + strs [j];} floderPath = floderPath + "\" + strs [I]; Directory. createDirectory (floderPath);} fs = new FileStream (_ floderPath + "\" + ze. name, FileMode. op EnOrCreate, FileAccess. write); // create a file // read the file to the file stream cyclically while (true) {byte [] bts = new byte [1024]; int I = InpStream. read (bts, 0, bts. length); if (I> 0) {fs. write (bts, 0, I);} else {fs. flush (); fs. close (); break ;}}ze = InpStream. getNextEntry () ;}} catch (Exception ex) {if (fs! = Null) {fs. Close () ;}errormsg = ex. Message; result = false;} return result ;}

 

Finally, let's make a summary. C # as an advanced language, its powerful class libraries and third-party class libraries. You can do many things. However, the performance of third-party class libraries is not very high. I compress hundreds of MB of data. The cpu instantly reaches more than 50%. This is far worse than 360 compression and zip compression. Therefore, this class applies to small compression.

Complete example

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.