In the enterprise development process often encounter file compression and decompression, although many popular compressed file format on the Web is RAR, but because RAR is not an open standard, so zip becomes more people's choice. If you do not want to develop yourself, you can choose Open source projects, such as SharpZipLib is a good choice.
usingSystem;usingSystem.Collections.Generic;usingSystem.Text;usingSystem.IO;usingICSharpCode.SharpZipLib.Zip;usingSystem.Diagnostics;usingICSharpCode.SharpZipLib.Core;namespacetestconsole{classProgram {Static voidMain () {//createzipfile (@ "d:\", @ "D:\a.zip");Unzipfile (@"D:\a.zip"); Console.read (); } Private Static voidCreatezipfile (stringFilespath,stringZipfilepath) { if(!directory.exists (Filespath)) {Console.WriteLine ("cannot find directory ' {0} '", Filespath); return; } Try { string[] filenames =Directory.GetFiles (Filespath); using(Zipoutputstream s =NewZipoutputstream (File.create (Zipfilepath))) {S.setlevel (9);//compression level 0-9//S.password = "123";//Zip compressed file password byte[] buffer =New byte[4096];//Buffer size foreach(stringFileinchfilenames) {ZipEntry entry=Newzipentry (path.getfilename (file)); Entry. DateTime=DateTime.Now; S.putnextentry (entry); using(FileStream fs =File.openread (File)) { intsourcebytes; Do{sourcebytes= fs. Read (Buffer,0, buffer. Length); S.write (Buffer,0, sourcebytes); } while(Sourcebytes >0); }} s.finish (); S.close (); } } Catch(Exception ex) {Console.WriteLine ("Exception during processing {0}", ex); } } Private Static voidUnzipfile (stringZipfilepath) { if(!file.exists (Zipfilepath)) {Console.WriteLine ("cannot find file ' {0} '", Zipfilepath); return; } using(Zipinputstream s =NewZipinputstream (File.openread (Zipfilepath))) {ZipEntry theentry; while((Theentry = S.getnextentry ())! =NULL) {Console.WriteLine (theentry.name); stringDirectoryName =Path.getdirectoryname (theentry.name); stringFileName =Path.getfilename (theentry.name); //Create directory if(Directoryname.length >0) {directory.createdirectory (directoryname); } if(FileName! =String.Empty) {using(FileStream StreamWriter =file.create (Theentry.name)) { intSize =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; } } } } } } } }}< /c5>
C # File compression and decompression (zip format)