Use ICSharpCode. SharpZipLib. dll in C # To Compress and decompress files/folders.

Source: Internet
Author: User
Tags crc32

Use ICSharpCode. SharpZipLib. dll in C # To Compress and decompress files/folders.

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
 
  
LogsInOneDay = new List
  
   
(); 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 = Guid. newGuid (); compressFileName = compressFileName + "-" + guid. toString ();} compressFileName + = ". zip "; Compress (logsInOneDay, logsDic. fullName + "\ CompressionDirectory \" + compressFileName, 9,100); foreach (FileInfo 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. getFiles (); List
 
  
LogsInOneDay = new List
  
   
(); 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 = Guid. newGuid (); compressFileName = compressFileName + "-" + guid. toString ();} compressFileName + = ". zip "; Compress (logsInOneDay, bankDic. fullName + "\ CompressionDirectory \" + compressFileName, 9,100); foreach (FileInfo 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 ////// Compressed file //////List of files to be packaged///Target file name///Compression Quality level (0 ~ 9)///Sleep Time (unit: milliseconds)Public static void Compress (List
 
  
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;} // reads 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 ////// Decompress the file //////Compressed package file name///Decompress the target pathPublic 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 ////// Compress the folder //////Folder to be packaged///Target file name///Compression Quality level (0 ~ 9)///Delete original folder?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 zipoutputstream = new ZipOutputStream (File. create (GzipFileName) {zipoutputstream. setLevel (CompressionLevel); ICSharpCode. sharpZipLib. checksums. crc32 crc = new ICSharpCode. sharpZipLib. checksums. crc32 (); Dictionary
 
  
FileList = GetAllFies (dirPath); foreach (KeyValuePair
  
   
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 under the Dir DIRECTORY parameter (EG: GetAllFies (@ "F: \ WorkSpace") to get all files under the F disk WorkSpace directory)

# Region get all files ////// Obtain all objects //////
 Private static Dictionary
 
  
GetAllFies (string dir) {Dictionary
  
   
FilesList = new Dictionary
   
    
(); 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 ////// Get the files in all folders in a folder /////////Private static void GetAllDirsFiles (DirectoryInfo [] dirs, Dictionary
 
  
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 ////// Get the file in a folder //////Directory Name///File List HastTablePrivate static void GetAllDirFiles (DirectoryInfo dir, Dictionary
 
  
FilesList) {foreach (FileInfo file in dir. GetFiles ("*. *") {filesList. Add (file. FullName, file. LastWriteTime) ;}# endregion
 










Related Article

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.