Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

Net what is the decompression component SharpZipLib for multi-type files

2025-01-19 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/03 Report--

This article is to share with you about the .NET multi-type file decompression component SharpZipLib is how, the editor feels very practical, so share with you to learn, I hope you can learn something after reading this article, say no more, follow the editor to have a look.

Extract the component SharpZipLib.

SharpZipLib is a Zip,GZip,Tar and BZip2 library written entirely in C # for the .NET platform.

I. Overview of SharpZipLib components:

Ziplib (SharpZipLib, formerly NZipLib) is a Zip,GZip,Tar and BZip2 library written entirely in C # for the .NET platform. It is implemented as an assembly (which can be installed in GAC), so it can be easily integrated into other projects (any .NET language). The creator of # ziplib said: "I have migrated the zip library to C # because I need gzip / zip compression, and I don't want to use libzip.dll or something like that all I want in pure C #."

SharpZipLib official website provides the download operation:. NET 1.1 KB; .NET 2.0 (3.5 CF 4.0),. NET CF 1.0 CF 2.0 assembly: download 237 KB, source code and samples download 708 KB; help files download 1208 KB

SharpZipLib is released under GPL and follows the open source agreement.

2. Introduction to SharpZipLib core classes and methods:

The above briefly introduces the relevant background of the SharpZipLib component, now take a specific look at the relevant core classes and methods of the component:

1.ZipOutputStream class PutNextEntry ():

Public void PutNextEntry (ZipEntry entry) {bool hasCrc; if (entry = = null) {throw new ArgumentNullException ("entry");} if (this.entries = = null) {throw new InvalidOperationException ("ZipOutputStream was finished");} if (this.curEntry! = null) {this.CloseEntry ();} if (this.entries.Count = = 0x7fffffff) {throw new ZipException ("Too many entries for Zip file");} CompressionMethod compressionMethod = entry.CompressionMethod; int defaultCompressionLevel = this.defaultCompressionLevel Entry.Flags & = 0x800; this.patchEntryHeader = false; if (entry.Size = = 0L) {entry.CompressedSize = entry.Size; entry.Crc = 0L; compressionMethod = CompressionMethod.Stored; hasCrc = true;} else {hasCrc = (entry.Size > = 0L) & & entry.HasCrc If (compressionMethod = = CompressionMethod.Stored) {if (! hasCrc) {if (! base.CanPatchEntries) {compressionMethod = CompressionMethod.Deflated; defaultCompressionLevel = 0;}} else {entry.CompressedSize = entry.Size; hasCrc = entry.HasCrc } if (! hasCrc) {if (! base.CanPatchEntries) {entry.Flags | = 8;} else {this.patchEntryHeader = true;}} if (base.Password! = null) {entry.IsCrypted = true; if (entry.Crc

< 0L) { entry.Flags |= 8; } } entry.Offset = this.offset; entry.CompressionMethod = compressionMethod; this.curMethod = compressionMethod; this.sizePatchPos = -1L; if ((this.useZip64_ == UseZip64.On) || ((entry.Size < 0L) && (this.useZip64_ == UseZip64.Dynamic))) { entry.ForceZip64(); } this.WriteLeInt(0x4034b50); this.WriteLeShort(entry.Version); this.WriteLeShort(entry.Flags); this.WriteLeShort((byte) entry.CompressionMethodForHeader); this.WriteLeInt((int) entry.DosTime); if (hasCrc) { this.WriteLeInt((int) entry.Crc); if (entry.LocalHeaderRequiresZip64) { this.WriteLeInt(-1); this.WriteLeInt(-1); } else { this.WriteLeInt(entry.IsCrypted ? (((int) entry.CompressedSize) + 12) : ((int) entry.CompressedSize)); this.WriteLeInt((int) entry.Size); } } else { if (this.patchEntryHeader) { this.crcPatchPos = base.baseOutputStream_.Position; } this.WriteLeInt(0); if (this.patchEntryHeader) { this.sizePatchPos = base.baseOutputStream_.Position; } if (entry.LocalHeaderRequiresZip64 || this.patchEntryHeader) { this.WriteLeInt(-1); this.WriteLeInt(-1); } else { this.WriteLeInt(0); this.WriteLeInt(0); } } byte[] buffer = ZipConstants.ConvertToArray(entry.Flags, entry.Name); if (buffer.Length >

0xffff) {throw new ZipException ("Entry name too long.");} ZipExtraData extraData = new ZipExtraData (entry.ExtraData); if (entry.LocalHeaderRequiresZip64) {extraData.StartNewEntry (); if (hasCrc) {extraData.AddLeLong (entry.Size); extraData.AddLeLong (entry.CompressedSize);} else {extraData.AddLeLong (- 1L); extraData.AddLeLong (- 1L);} extraData.AddNewEntry (1) If (! extraData.Find (1)) {throw new ZipException ("Internal error cant find extra data");} if (this.patchEntryHeader) {this.sizePatchPos = extraData.CurrentReadIndex;}} else {extraData.Delete (1);} if (entry.AESKeySize > 0) {AddExtraDataAES (entry, extraData);} byte [] entryData = extraData.GetEntryData (); this.WriteLeShort (buffer.Length); this.WriteLeShort (entryData.Length) If (buffer.Length > 0) {base.baseOutputStream_.Write (buffer, 0, buffer.Length);} if (entry.LocalHeaderRequiresZip64 & & this.patchEntryHeader) {this.sizePatchPos + = base.baseOutputStream_.Position;} if (entryData.Length > 0) {base.baseOutputStream_.Write (entryData, 0, entryData.Length);} this.offset + = (30 + buffer.Length) + entryData.Length; if (entry.AESKeySize > 0) {this.offset + = entry.AESOverheadSize } this.curEntry = entry; this.crc.Reset (); if (compressionMethod = = CompressionMethod.Deflated) {base.deflater_.Reset (); base.deflater_.SetLevel (defaultCompressionLevel);} this.size = 0L; if (entry.IsCrypted) {if (entry.AESKeySize > 0) {this.WriteAESHeader (entry);} else if (entry.Crc)

< 0L) { this.WriteEncryptionHeader(entry.DosTime = 0xffffffffL)) { this.WriteLeInt(-1); } else { this.WriteLeInt((int) entry.CompressedSize); } if (entry.IsZip64Forced() || (entry.Size >

= 0xffffffffL) {this.WriteLeInt (- 1);} else {this.WriteLeInt ((int) entry.Size);} byte [] buffer = ZipConstants.ConvertToArray (entry.Flags, entry.Name); if (buffer.Length > 0xffff) {throw new ZipException ("Name too long.");} ZipExtraData extraData = new ZipExtraData (entry.ExtraData) If (entry.CentralHeaderRequiresZip64) {extraData.StartNewEntry (); if (entry.IsZip64Forced () | | (entry.Size > = 0xffffffffL)) {extraData.AddLeLong (entry.Size);} if (entry.IsZip64Forced () | | (entry.CompressedSize > = 0xffffffffL)) {extraData.AddLeLong (entry.CompressedSize) } if (entry.Offset > = 0xffffffffL) {extraData.AddLeLong (entry.Offset);} extraData.AddNewEntry (1);} else {extraData.Delete (1);} if (entry.AESKeySize > 0) {AddExtraDataAES (entry, extraData);} byte [] entryData = extraData.GetEntryData () Byte [] buffer3 = (entry.Comment! = null)? ZipConstants.ConvertToArray (entry.Flags, entry.Comment): new byte [0]; if (buffer3.Length > 0xffff) {throw new ZipException ("Comment too long.");} this.WriteLeShort (buffer.Length); this.WriteLeShort (entryData.Length); this.WriteLeShort (buffer3.Length); this.WriteLeShort (0); this.WriteLeShort (0) If (entry.ExternalFileAttributes! =-1) {this.WriteLeInt (entry.ExternalFileAttributes);} else if (entry.IsDirectory) {this.WriteLeInt (0x10);} else {this.WriteLeInt (0);} if (entry.Offset > = 0xffffffffL) {this.WriteLeInt (- 1) } else {this.WriteLeInt ((int) entry.Offset);} if (buffer.Length > 0) {base.baseOutputStream_.Write (buffer, 0, buffer.Length);} if (entryData.Length > 0) {base.baseOutputStream_.Write (entryData, 0, entryData.Length) } if (buffer3.Length > 0) {base.baseOutputStream_.Write (buffer3, 0, buffer3.Length);} sizeEntries + = ((0x2e + buffer.Length) + entryData.Length) + buffer3.Length;} using (ZipHelperStream stream = new ZipHelperStream (base.baseOutputStream_)) {stream.WriteEndOfCentralDirectory (count, sizeEntries, this.offset, this.zipComment);} this.entries = null;}}

3.ZipEntry class Clone ():

Public object Clone () {ZipEntry entry = (ZipEntry) base.MemberwiseClone (); if (this.extra! = null) {entry.extra = new byte [this.extra.Length]; Array.Copy (this.extra, 0, entry.extra, 0, this.extra.Length);} return entry;}

4.ZipOutputStream class Write ():

Public override void Write (byte [] buffer, int offset, int count) {if (this.curEntry = = null) {throw new InvalidOperationException ("No open entry.");} if (buffer = = null) {throw new ArgumentNullException ("buffer");} if (offset)

< 0) { throw new ArgumentOutOfRangeException("offset", "Cannot be negative"); } if (count < 0) { throw new ArgumentOutOfRangeException("count", "Cannot be negative"); } if ((buffer.Length - offset) < count) { throw new ArgumentException("Invalid offset/count combination"); } this.crc.Update(buffer, offset, count); this.size += count; switch (this.curMethod) { case CompressionMethod.Stored: if (base.Password != null) { this.CopyAndEncrypt(buffer, offset, count); } else { base.baseOutputStream_.Write(buffer, offset, count); } break; case CompressionMethod.Deflated: base.Write(buffer, offset, count); break; }} 三.SharpZipLib实例: 1.压缩单个文件: /// /// 压缩单个文件 /// /// 要压缩的文件 /// 压缩后的文件 /// 压缩等级 /// 每次写入大小 public static void ZipFile(string fileToZip, string zipedFile, int compressionLevel, int blockSize) { if (string.IsNullOrEmpty(fileToZip)) { throw new ArgumentNullException(fileToZip); } if (string.IsNullOrEmpty(zipedFile)) { throw new ArgumentNullException(zipedFile); } if (!File.Exists(fileToZip)) { throw new FileNotFoundException("指定要压缩的文件: " + fileToZip + " 不存在!"); } try { using (var zipFile = File.Create(zipedFile)) { using (var zipStream = new ZipOutputStream(zipFile)) { using (var streamToZip = new FileStream(fileToZip, FileMode.Open, FileAccess.Read)) { var fileName = fileToZip.Substring(fileToZip.LastIndexOf("\\", StringComparison.Ordinal) + 1); var zipEntry = new ZipEntry(fileName); zipStream.PutNextEntry(zipEntry); zipStream.SetLevel(compressionLevel); var buffer = new byte[blockSize]; try { int sizeRead; do { sizeRead = streamToZip.Read(buffer, 0, buffer.Length); zipStream.Write(buffer, 0, sizeRead); } while (sizeRead >

0);} catch (Exception ex) {throw new Exception (ex.Message);} streamToZip.Close ();} zipStream.Finish (); zipStream.Close ();} zipFile.Close () }} catch (IOException ioex) {throw new IOException (ioex.Message);} catch (Exception ex) {throw new Exception (ex.Message);}}

two。 Compress a single file:

/ compress a single file / File name to be compressed / compressed file name public static void ZipFile (string fileToZip, string zipedFile) {if (string.IsNullOrEmpty (fileToZip)) {throw new ArgumentException (fileToZip);} if (string.IsNullOrEmpty (zipedFile)) {throw new ArgumentException (zipedFile) } if (! File.Exists (fileToZip)) {throw new FileNotFoundException ("specify the file to be compressed:" + fileToZip + "does not exist!");} try {using (var fs = File.OpenRead (fileToZip)) {var buffer = new byte [fs.Length]; fs.Read (buffer, 0, buffer.Length); fs.Close () Using (var zipFile = File.Create (zipedFile)) {using (var zipStream = new ZipOutputStream (zipFile)) {var fileName = fileToZip.Substring (fileToZip.LastIndexOf ("\\", StringComparison.Ordinal) + 1); var zipEntry = new ZipEntry (fileName); zipStream.PutNextEntry (zipEntry); zipStream.SetLevel (5) ZipStream.Write (buffer, 0, buffer.Length); zipStream.Finish (); zipStream.Close ();} catch (IOException ioex) {throw new IOException (ioex.Message);} catch (Exception ex) {throw new Exception (ex.Message);}}

3. Compress multi-tier directories:

/ / compress multi-tier directory / directory / compressed file public static void ZipFileDirectory (string strDirectory, string zipedFile) {if (string.IsNullOrEmpty (strDirectory)) {throw new ArgumentException (strDirectory);} if (string.IsNullOrEmpty (zipedFile)) {throw new ArgumentException (zipedFile) } using (var zipFile = File.Create (zipedFile)) {using (var s = new ZipOutputStream (zipFile)) {ZipSetp (strDirectory, s, "");}

4. Recursively traverse the directory:

/ Recursively traverse the directory / directory / ZipOutputStream object / parent path private static void ZipSetp (string strDirectory, ZipOutputStream s, string parentPath) {if (strDirectory [strDirectory.Length-1]! = Path.DirectorySeparatorChar) {strDirectory + = Path.DirectorySeparatorChar;} var crc = new Crc32 (); var filenames = Directory.GetFileSystemEntries (strDirectory) Try {/ / traverses all files and directories foreach (var file in filenames) {/ / treat it as a directory if it exists, recursively Copy the files under that directory if (Directory.Exists (file)) {var pPath = parentPath PPath + = file.Substring (file.LastIndexOf ("\\", StringComparison.Ordinal) + 1); pPath + = "\"; ZipSetp (file, s, pPath) } / / otherwise directly compress the file else {/ / Open the compressed file using (var fs = File.OpenRead (file)) {var buffer = new byte [fs.Length]; fs.Read (buffer, 0, buffer.Length) Var fileName = parentPath + file.Substring (file.LastIndexOf ("\", StringComparison.Ordinal) + 1); var entry = new ZipEntry (fileName) {DateTime = DateTime.Now, Size = fs.Length}; fs.Close (); crc.Reset (); crc.Update (buffer) Entry.Crc = crc.Value; s.PutNextEntry (entry); s.Write (buffer, 0, buffer.Length);} catch (IOException ioex) {throw new IOException (ioex.Message);} catch (Exception ex) {throw new Exception (ex.Message);}}

5. Extract an zip file:

/ / extract a zip file. / The ziped file. / The STR directory. / / password of the zip file. / / whether to overwrite existing files. Public void UnZip (string zipedFile, string strDirectory, string password, bool overWrite) {if (string.IsNullOrEmpty (zipedFile)) {throw new ArgumentException (zipedFile);} if (string.IsNullOrEmpty (strDirectory)) {throw new ArgumentException (strDirectory);} if (string.IsNullOrEmpty (password)) {throw new ArgumentException (password) } if (strDirectory = = ") {strDirectory = Directory.GetCurrentDirectory ();} if (! strDirectory.EndsWith ("\\ ")) {strDirectory = strDirectory +"\ ";} try {using (var s = new ZipInputStream (File.OpenRead (zipedFile) {s.Password = password; ZipEntry theEntry While ((theEntry = s.GetNextEntry ())! = null) {var directoryName = string.Empty; var pathToZip = theEntry.Name; if (pathToZip! = "") {directoryName = Path.GetDirectoryName (pathToZip) + "\";} var fileName = Path.GetFileName (pathToZip) Directory.CreateDirectory (strDirectory + directoryName); if (fileName = "") continue; if ((! File.Exists (strDirectory + directoryName + fileName) | |! overWrite) & & (File.Exists (strDirectory + directoryName + fileName)) continue; using (var streamWriter = File.Create (strDirectory + directoryName + fileName)) {var data = new byte [2048] While (true) {var size = s.Read (data, 0, data.Length); if (size > 0) streamWriter.Write (data, 0, size); else break;} streamWriter.Close () }} s.Close ();}} catch (IOException ioex) {throw new IOException (ioex.Message);} catch (Exception ex) {throw new Exception (ex.Message);}}

The above is the relevant introduction of SharpZipLib components, the explanation of this article is relatively simple, if you need in-depth study, you can enter the official website for detailed study. The function of the component is very powerful, how to use the component in the project to complete the function that we need to achieve in the project, this is the requirement for every developer, we need to consider carefully.

This is what the .NET multi-type file decompression component SharpZipLib is like, and the editor believes that there are some knowledge points that we may see or use in our daily work. I hope you can learn more from this article. For more details, please follow the industry information channel.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report