Use icsharpcode. sharpziplib. dll in C # To Compress and decompress files/folders.

Source: Internet
Author: User
Tags crc32

Icsharpcode. sharpziplib. dll

1. compress the logs in a specified directory, compress the logs to the compressiondirectory folder, and clear the uncompressed logs.

# Region: compresslogdic () {try {string logfilepath = appdomain. currentdomain. basedirectory + "logs"; directoryinfo logsdic = new directoryinfo (logfilepath); fileinfo [] biplog = logsdic. getfiles (); datetime dt = datetime. now; List <fileinfo> logsinoneday = new list <fileinfo> (); For (INT I = 0; I <biplog. length; I ++) {If (biplog [I]. name. substring (biplog [I]. name. length -3 )! = "Zip") {logsinoneday. Add (biplog [I]) ;}} if (logsinoneday. Count> 0) {try {If (! Directory. exists (logsdic. fullname + "\ compressiondirectory") {directory. createdirectory (logsdic. fullname + "\ compressiondirectory");} string compressfilename = DT. tostring ("yyyy-mm-dd"); If (file. exists (logsdic. fullname + "\ compressiondirectory \" + dt. tostring ("yyyy-mm-dd") + ". zip ") {guid = guid. newguid (); compressfilename = compressfilename + "-" + guid. tostring ();} compressfilename + = ". zip "; compress (logsinoneday, logsdic. fullname + "\ compressiondirectory \" + compressfilename, 9,100); foreach (fileinfo in logsinoneday) {try {fileinfo. delete ();} catch (exception e) {// handle error information} catch (exception e) {// handle error message records} catch (exception E) {// error message record processing} # endregion
2. compressiondirectory: compressiondirectory.

# Region compresslogsdic () {try {string logfilepath = appdomain. currentdomain. basedirectory + "logs"; directoryinfo logsdic = new directoryinfo (logfilepath); fileinfo [] biplog = logsdic. getfiles (); datetime dt = datetime. now; directoryinfo [] sublosgdic = logsdic. getdirectories (); foreach (directoryinfo bankdic in sublosgdic) {dt = datetime. now; biplog = bankdic. get Files (); List <fileinfo> logsinoneday = new list <fileinfo> (); For (INT I = 0; I <biplog. length; I ++) {If (biplog [I]. name. substring (biplog [I]. name. length-3 )! = "Zip") {logsinoneday. Add (biplog [I]) ;}} if (logsinoneday. Count> 0) {try {If (! Directory. exists (bankdic. fullname + "\ compressiondirectory") {directory. createdirectory (bankdic. fullname + "\ compressiondirectory");} string compressfilename = DT. tostring ("yyyy-mm-dd"); If (file. exists (bankdic. fullname + "\ compressiondirectory \" + dt. tostring ("yyyy-mm-dd") + ". zip ") {guid = guid. newguid (); compressfilename = compressfilename + "-" + guid. tostring ();} compressfilename + = ". zip "; compress (logsinoneday, bankdic. fullname + "\ compressiondirectory \" + compressfilename, 9,100); foreach (fileinfo in logsinoneday) {try {fileinfo. delete ();} catch (exception e) {// handle error messages }}} catch (exception E) {// error message record processing }}} catch (exception e) {// error message record processing }}# endregion
3. compressed files

# Region compressed file /// <summary> // compressed file /// </Summary> /// <Param name = "filenames"> list of files to be packaged </ param> /// <Param name = "gzipfilename"> target file name </param> /// <Param name = "compressionlevel"> compression quality level (0 ~ 9) </param> // <Param name = "sleeptimer"> sleep time (unit: milliseconds) </param> Public static void compress (list <fileinfo> filenames, string gzipfilename, int compressionlevel, int sleeptimer) {zipoutputstream S = new zipoutputstream (file. create (gzipfilename); try {S. setlevel (compressionlevel); // 0-store only to 9-means best compression foreach (fileinfo file in filenames) {filestream FS = NULL; try {FS = File. Open (filemode. open, fileaccess. readwrite);} catch {continue;} // read files in batches into the buffer byte [] DATA = new byte [2048]; int size = 2048; zipentry entry = new zipentry (path. getfilename (file. name); entry. datetime = (file. creationtime> file. lastwritetime? File. lastwritetime: file. creationtime); S. putnextentry (entry); While (true) {size = FS. read (data, 0, size); If (size <= 0) break; S. write (data, 0, size);} FS. close (); thread. sleep (sleeptimer) ;}} finally {S. finish (); S. close () ;}# endregion
4. Extract
# Region decompress the file /// <summary> /// decompress the file /// </Summary> /// <Param name = "gzipfile"> compressed package file name </param>/ // <Param name = "targetpath"> decompress the target path </param> Public static void decompress (string gzipfile, string targetpath) {// string directoryname = path. getdirectoryname (targetpath + "//") + "//"; string directoryname = targetpath; If (! Directory. exists (directoryname) directory. createdirectory (directoryname); // generate the extract directory string currentdirectory = directoryname; byte [] DATA = new byte [2048]; int size = 2048; zipentry theentry = NULL; using (zipinputstream S = new zipinputstream (file. openread (gzipfile) {While (theentry = S. getnextentry ())! = NULL) {If (theentry. isdirectory) {// This node is the directory if (! Directory. exists (currentdirectory + theentry. Name) directory. createdirectory (currentdirectory + theentry. Name);} else {If (theentry. Name! = String. empty) {// check whether the multi-level directory exists if (theentry. name. contains ("//") {string parentdirpath = theentry. name. remove (theentry. name. lastindexof ("//") + 1); If (! Directory. exists (parentdirpath) {directory. createdirectory (currentdirectory + parentdirpath) ;}// extract the file to the specified directory using (filestream streamwriter = file. create (currentdirectory + theentry. name) {While (true) {size = S. read (data, 0, Data. length); If (size <= 0) break; streamwriter. write (data, 0, size);} streamwriter. close () ;}}} S. close () ;}# endregion
5. compressing folders

# Region compressed folder /// <summary> // compressed folder /// </Summary> /// <Param name = "dirpath"> folder to be packaged </Param> /// <Param name = "gzipfilename"> target file name </param> /// <Param name = "compressionlevel"> compression quality level (0 ~ 9) </param> // <Param name = "deletedir"> whether to delete the original folder </param> Public static void compressdirectory (string dirpath, string gzipfilename, int compressionlevel, bool deletedir) {// when the compressed file is empty, if (gzipfilename = string. empty) {gzipfilename = dirpath. substring (dirpath. lastindexof ("//") + 1); gzipfilename = dirpath. substring (0, dirpath. lastindexof ("//") + "//" + gzipfilename + ". zip ";} // If (Path. Getextension (gzipfilename )! = ". Zip ") // {// gzipfilename = gzipfilename + ". zip "; //} using (zipoutputstream = new zipoutputstream (file. create (gzipfilename) {zipoutputstream. setlevel (compressionlevel); icsharpcode. sharpziplib. checksums. CRC32 CRC = new icsharpcode. sharpziplib. checksums. CRC32 (); dictionary <string, datetime> filelist = getallfies (dirpath); foreach (keyvaluepair <string, datetime> item in filelist) {filestream FS = file. openread (item. key. tostring (); byte [] buffer = new byte [FS. length]; FS. read (buffer, 0, buffer. length); zipentry entry = new zipentry (item. key. substring (dirpath. length); entry. datetime = item. value; entry. size = FS. length; FS. close (); CRC. reset (); CRC. update (buffer); entry. CRC = CRC. value; zipoutputstream. putnextentry (entry); zipoutputstream. write (buffer, 0, buffer. length) ;}} if (deletedir) {directory. delete (dirpath, true) ;}# endregion
6. Get all files

# Region get all files /// <summary> /// get all files /// </Summary> /// <returns> </returns> Private Static dictionary <string, datetime> getallfies (string DIR) {dictionary <string, datetime> fileslist = new dictionary <string, datetime> (); directoryinfo filedire = new directoryinfo (DIR); If (! Filedire. exists) {Throw new system. Io. filenotfoundexception ("Directory:" + filedire. fullname + "not found! ");} Getalldirfiles (filedire, fileslist); getalldirsfiles (filedire. getdirectories (), fileslist); Return fileslist;} # endregion
7. Get the files in all folders in a folder

# Region get the files in all folders in a folder /// <summary> /// get the files in all folders in a folder /// </Summary> // /<Param name = "dirs"> </param> // <Param name = "fileslist"> </param> Private Static void getalldirsfiles (directoryinfo [] dirs, dictionary <string, datetime> fileslist) {foreach (directoryinfo dir in dirs) {foreach (fileinfo file in Dir. getfiles ("*. * ") {fileslist. add (file. fullname, file. lastwritetime);} getalldirsfiles (dir. getdirectories (), fileslist) ;}# endregion
8. Get files in a folder

# Region get the file in a folder /// <summary> /// get the file in a folder /// </Summary> /// <Param name = "dir"> directory name </param> /// <Param name = "fileslist"> file list hasttable </param> Private Static void getalldirfiles (directoryinfo Dir, dictionary <string, datetime> fileslist) {foreach (fileinfo file in Dir. getfiles ("*. * ") {fileslist. add (file. fullname, file. lastwritetime) ;}# endregion










Use icsharpcode. sharpziplib. dll in C # To Compress and decompress files/folders.

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.