C # ZIP file compression and decompression code

Source: Internet
Author: User

Compression and decompression can be divided into single file compression and whole folder compression. Folder compression has not yet implemented recursive folder, and is now enough to pass the test. The Code is as follows:

Using system; using system. collections. generic; using system. LINQ; using system. text; using system. io; using system. io. compression; using system. collections; using system. runtime. serialization. formatters. binary; using system. runtime. serialization; namespace common {// <summary> /// compressed file /// </Summary> public class zip {# region compression decompress a single file /// <summary> /// compress a single file /// </Summary> /// <Param name = "sourcefile"> Source File Path </param> /// <Param name = "destinationfile"> target file path </param> Public static void compressfile (string sourcefile, string destinationfile) {If (! File. exists (sourcefile) throw new filenotfoundexception (); Using (filestream sourcestream = new filestream (sourcefile, filemode. open, fileaccess. read, fileshare. read) {byte [] buffer = new byte [sourcestream. length]; int checkcounter = sourcestream. read (buffer, 0, buffer. length); If (checkcounter! = Buffer. length) throw new applicationexception (); Using (filestream destinationstream = new filestream (destinationfile, filemode. openorcreate, fileaccess. write) {using (gzipstream compressedstream = new gzipstream (destinationstream, compressionmode. compress, true) {compressedstream. write (buffer, 0, buffer. length) ;}}} public static void compressfile (byte [] source, string destinationfile ){ Using (filestream destinationstream = new filestream (destinationfile, filemode. openorcreate, fileaccess. write) {using (gzipstream compressedstream = new gzipstream (destinationstream, compressionmode. compress, true) {compressedstream. write (source, 0, source. length );}}} /// <summary> /// decompress the file /// </Summary> /// <Param name = "sourcefile"> source file path </param> /// <Param name = "destinationfile"> target file path </Param> Public static void decompressfile (string sourcefile, string destinationfile) {If (! File. exists (sourcefile) throw new filenotfoundexception (); Using (filestream sourcestream = new filestream (sourcefile, filemode. open) {byte [] quartetbuffer = new byte [4]; int position = (INT) sourcestream. length-4; sourcestream. position = position; sourcestream. read (quartetbuffer, 0, 4); sourcestream. position = 0; int checklength = bitconverter. toint32 (quartetbuffer, 0); byte [] buffer = new BYT E [checklength + 100]; using (gzipstream decompressedstream = new gzipstream (sourcestream, compressionmode. decompress, true) {int Total = 0; For (INT offset = 0;) {int bytesread = decompressedstream. read (buffer, offset, 100); If (bytesread = 0) break; offset + = bytesread; Total + = bytesread;} using (filestream destinationstream = new filestream (destinationfile, filemode. create) {destinati Onstream. write (buffer, 0, total); destinationstream. flush () ;}}# endregion # region compressed and decompressed Folder/*** /// <summary> // compress the target folder, save the compression result as the specified file // </Summary> /// <Param name = "dirpath"> destination folder </param> /// <Param name = "FILENAME ""> compressed file </param> Public static void compressfolder (string dirpath, string filename) {arraylist list = new arraylist (); foreach (string F in directory. getfiles (dirpath) {byte [] Destbuffer = file. readallbytes (f); serializefileinfo SFI = new serializefileinfo (F, destbuffer); list. add (SFI);} iformatter formatter = new binaryformatter (); Using (Stream S = new memorystream () {formatter. serialize (S, list); S. position = 0; createcompressfile (S, filename) ;}}/** // <summary> // decompress the target compressed file, extract the content to the specified folder /// </Summary> /// <Param name = "FILENAME"> compressed file </param> /// <Param name = "Dirpath"> extract directory </param> Public static void decompressfolder (string filename, string dirpath) {using (stream source = file. openread (filename) {using (Stream Destination = new memorystream () {using (gzipstream input = new gzipstream (source, compressionmode. decompress, true) {byte [] bytes = new byte [4096]; int N; while (n = input. read (bytes, 0, bytes. length ))! = 0) {destination. write (bytes, 0, n) ;}} destination. flush (); destination. position = 0; deserializefiles (destination, dirpath) ;}} Private Static void deserializefiles (Stream S, string dirpath) {binaryformatter B = new binaryformatter (); arraylist list = (arraylist) b. deserialize (s); foreach (serializefileinfo F in list) {string newname = dirpath + path. getfilename (F. filename); Using (filestr Eam fs = new filestream (newname, filemode. create, fileaccess. write) {FS. write (F. filebuffer, 0, F. filebuffer. length); FS. close () ;}} Private Static void createcompressfile (stream source, string destinationname) {using (Stream Destination = new filestream (destinationname, filemode. create, fileaccess. write) {using (gzipstream output = new gzipstream (destination, compressionmode. compress) {B Yte [] bytes = new byte [4096]; int N; while (n = source. Read (bytes, 0, bytes. Length ))! = 0) {output. write (bytes, 0, n) ;}}}# endregion} // test // Private void btnzip_click (Object sender, eventargs e) // {// common. zip. compressfile ("database. mdb "," test.zip "); // common. zip. compressfolder ("sourcefolder", "sourcefolder.zip"); // Private void btnunzip_click (Object sender, eventargs e) // {// common. zip. decompressfile ("test.zip", "database2.mdb"); // common. zip. decompressfolder ("sourcefolder.zip", "folder/"); //} [serializable] class serializefileinfo {public serializefileinfo (string name, byte [] buffer) {filename = Name; filebuffer = buffer;} string filename; Public String filename {get {return filename;} byte [] filebuffer; Public byte [] filebuffer {get {return filebuffer ;}}}}

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.