In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-04-02 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/03 Report--
How to use the .NET open source free ZIP library DotNetZip, I believe that many inexperienced people do not know what to do, so this article summarizes the causes of the problem and solutions, through this article I hope you can solve this problem.
In project development, in addition to the display of data, there are more operations related to files, such as file creation and deletion, as well as file compression and decompression. There are many benefits of file compression, mainly in the aspect of file transfer, the benefits of file compression do not need to be mentioned, because both developers and users have a deep understanding of the benefits of file compression.
Net provides two compression algorithms, GZip and Defalate, in the System.IO.Compression namespace. One compression component I'm going to introduce today is the DotNetZip component.
I. Overview of DotNetZip components:
In DotNetZip's self-introduction, it is known as "DotNetZip is the best open source ZIP library in .NET". As for whether it is the best compressed component, there is no evaluation here. After all, each user's mentality and working environment are different, and the project's requirements for components are also different. When selecting components, developers need to measure them. It is estimated that many people have started typing on the keyboard to complain before they see it. The title is that I borrow the official slogan, so I don't have to pay too much attention to these details.
DotNetZip-Zip decompression is available in Clipper VB, any. Net language. DotNetZip is a FAST, free class library and toolset for manipulating zip files. Easily create, extract, or update zip files using VB,C# or any .NET language. DotNetZip runs on PC with full. NET Framework and also runs on mobile devices that use the .NET Compact Framework. Create and read zip files in VB,C# or any .NET language or any scripting environment.
The environment for the use of DotNetZip components, after all, the environment for the use of software is something that every developer needs to consider. There is no absolute good thing and no absolute bad thing in this world. Let's take a look at the description of its practical environment:
1. A Silverlight application that dynamically creates zip files.
two。 An ASP.NET application that dynamically creates ZIP files and allows browsers to download them.
3. A Windows service that periodically pulls up a directory for backup and archiving purposes.
4. Modify the WPF program for an existing archive-rename an entry, delete an entry from the archive, or add a new entry to the archive.
5. A Windows forms application that creates AES-encrypted zip archives for the privacy of archived content.
6. A SSIS script that unzips or zips.
An administrative script in 7.PowerShell or VBScript that performs backups and archives.
The 8.WCF service receives the zip file as an attachment and dynamically decompresses the zip to the stream for analysis.
9. An old ASP (VBScript) application that generates a ZIP file for DotNetZIp through the COM interface.
10. A Windows Forms application that reads or updates ODS files.
11. Create a zip file from the stream content, save it to the stream, extract it to the stream, and read from the stream.
twelve。 Create a self-extracting file.
DotNetZip is a 100% managed code base that can be used in any .NET application-console, Winforms,WPF,ASP.NET,Sharepoint,Web service application, etc. The new v1.9.1.6:Silverlight. It can also be used from scripting environments or environments with COM capabilities (such as Powershell scripts, VBScript,VBA,VB6,PHP,Perl,Javascript, etc.). Regardless of the environment used, the zip files generated by DotNetZip are fully interoperable with Windows Explorer and Java applications, applications running on Linux.
The component is simple in design and easy to use. DotNetZip is packaged into a single DLL with a size of about 400k. It has no third-party dependence. It is medium trust, so it can be used by most custodians. Get compression by referencing DLL. The library supports zip passwords, Unicode,ZIP64, stream input and output, AES encryption, multiple compression levels, self-extracting archiving, cross-region archiving, etc.
Some of the above descriptions come from the official website, so we no longer flatter this component. What we need to explain here is that the selection and use of the component mainly depends on the actual situation of the project. For details, please see: http://dotnetzip.codeplex.com/
2. Resolution of core classes and methods related to DotNetZip:
View the source code because you downloaded the DLL file or decompiled the DLL file using .NET Reflector. The main introduction of some classes and methods, not fully introduced, first of all, due to space constraints, in fact, it is completely unnecessary, because for developers, it is not necessary to understand all of these classes, in the actual development, can be based on API corresponding method calls, these skills should be a developer should have.
The AddEntry (), Save () and IsZipFile () methods of the 1.ZipFile class:
Public ZipEntry AddEntry (string entryName, WriteDelegate writer) {ZipEntry ze = ZipEntry.CreateForWriter (entryName, writer); if (this.Verbose) {this.StatusMessageTextWriter.WriteLine ("adding {0}...", entryName);} return this._InternalAddEntry (ze);} public void Save () {try {bool flag = false; this._saveOperationCanceled = false; this._numberOfSegmentsForMostRecentSave = 0; this.OnSaveStarted (); if (this.WriteStream = = null) {throw new BadStateException ("You haven't specified where to save the zip.") } if ((this._name! = null) & & this._name.EndsWith (".exe")) & &! this._SavingSfx) {throw new BadStateException ("You specified an EXE for a plain zip file.");} if (! this._contentsChanged) {this.OnSaveCompleted (); if (this.Verbose) {this.StatusMessageTextWriter.WriteLine ("No save is necessary....");}} else {this.Reset (true) If (this.Verbose) {this.StatusMessageTextWriter.WriteLine ("saving....");} if ((this._entries.Count > = 0xffff) & & (this._zip64 = = Zip64Option.Default)) {throw new ZipException ("The number of entries is 65535 or greater. Consider setting the UseZip64WhenSaving property on the ZipFile instance. ");} int current = 0; ICollection entries = this.SortEntriesBeforeSaving? This.EntriesSorted: this.Entries; foreach (ZipEntry entry in entries) {this.OnSaveEntry (current, entry, true); entry.Write (this.WriteStream); if (this._saveOperationCanceled) {break;} current++; this.OnSaveEntry (current, entry, false); if (this._saveOperationCanceled) {break;} if (entry.IncludedInMostRecentSave) {flag | = entry.OutputUsedZip64.Value }} if (! this._saveOperationCanceled) {ZipSegmentedStream writeStream = this.WriteStream as ZipSegmentedStream; this._numberOfSegmentsForMostRecentSave = (writeStream! = null)? WriteStream.CurrentSegment: 1; bool flag2 = ZipOutput.WriteCentralDirectoryStructure (this.WriteStream, entries, this._numberOfSegmentsForMostRecentSave, this._zip64, this.Comment, new ZipContainer (this)); this.OnSaveEvent (ZipProgressEventType.Saving_AfterSaveTempArchive); this._hasBeenSaved = true; this._contentsChanged = false; flag | = flag2; this._OutputUsesZip64 = new bool? (flag) If ((this._name! = null) & & ((this._temporaryFileName! = null) | | (writeStream! = null)) {this.WriteStream.Dispose (); if (this._saveOperationCanceled) {return;} if (this._fileAlreadyExists & & (this._readstream! = null)) {this._readstream.Close (); this._readstream = null Foreach (ZipEntry entry2 in entries) {ZipSegmentedStream stream2 = entry2._archiveStream as ZipSegmentedStream; if (stream2! = null) {stream2.Dispose ();} entry2._archiveStream = null;}} string path = null; if (File.Exists (this._name)) {path = this._name + "." + Path.GetRandomFileName () If (File.Exists (path)) {this.DeleteFileWithRetry (path);} File.Move (this._name, path);} this.OnSaveEvent (ZipProgressEventType.Saving_BeforeRenameTempArchive); File.Move ((writeStream! = null)? WriteStream.CurrentTempName: this._temporaryFileName, this._name); this.OnSaveEvent (ZipProgressEventType.Saving_AfterRenameTempArchive); if (path! = null) {try {if (File.Exists (path)) {File.Delete (path);} catch {} this._fileAlreadyExists = true;} NotifyEntriesSaveComplete (entries); this.OnSaveCompleted () This._JustSaved = true;}} finally {this.CleanupAfterSaveOperation ()}} public static bool IsZipFile (Stream stream, bool testExtract) {if (stream = = null) {throw new ArgumentNullException ("stream");} bool flag = false; try {if (! stream.CanRead) {return false;} Stream @ null = Stream.Null Using (ZipFile file = Read (stream, null, null, null)) {if (testExtract) {foreach (ZipEntry entry in file) {if (! entry.IsDirectory) {entry.Extract (@ null);} flag = true;} catch (IOException) {} catch (ZipException) {} return flag;}
2.Read () reads the data stream:
Private static ZipFile Read (Stream zipStream, TextWriter statusMessageWriter, Encoding encoding, EventHandler readProgress) {if (zipStream = = null) {throw new ArgumentNullException ("zipStream");} ZipFile zf = new ZipFile {_ StatusMessageTextWriter = statusMessageWriter, _ alternateEncoding = encoding?? DefaultEncoding, _ alternateEncodingUsage = ZipOption.Always}; if (readProgress! = null) {zf.ReadProgress + = readProgress;} zf._readstream = (zipStream.Position = = 0L)? ZipStream: new OffsetStream (zipStream); zf._ReadStreamIsOurs = false; if (zf.Verbose) {zf._StatusMessageTextWriter.WriteLine ("reading from stream...");} ReadIntoInstance (zf); return zf;}
The above is the parsing of some methods of the ZipFile class, providing the source code of some methods of the component, as for the interpretation of the source code is not very difficult, as for the API of the component, you can download the DLL file, you can directly view the corresponding methods and properties, do not do a detailed introduction here.
3. Examples of using DotNetZip components:
Here are some parsing of the component, let's take a look at the example:
1. Compress the ZIP file:
/ compressed ZIP files / supports multiple files and directories Or multi-file and multi-directory compression together / the compressed file name of the file or directory collection / whether the compressed file name is compressed according to the directory structure / success: true/ failed: false public static bool CompressMulti (List list, string strZipName, bool isDirStruct) {if (list = = null) {throw new ArgumentNullException ("list") } if (string.IsNullOrEmpty (strZipName)) {throw new ArgumentNullException (strZipName);} try {/ / set encoding to solve Chinese garbled using (var zip = new ZipFile (Encoding.Default)) {foreach (var path in list) {/ / take directory name var fileName = Path.GetFileName (path) when compressing files / / if it is the directory if (Directory.Exists (path)) {/ / compress if (isDirStruct) {zip.AddDirectory (path, fileName) according to the directory structure;} else {/ / the files under the directory are compressed to the root directory zip.AddDirectory (path) of Zip }} if (File.Exists (path)) {zip.AddFile (path);}} / / compress zip.Save (strZipName); return true;}} catch (Exception ex) {throw new Exception (ex.Message);}}
two。 Extract the ZIP file:
/ extract ZIP file / unzipped ZIP file / unzipped directory / / overwrite / success: true/ failed: false public static bool Decompression (string strZipPath, string strUnZipPath, bool overWrite) {if (string.IsNullOrEmpty (strZipPath)) {throw new ArgumentNullException (strZipPath);} if (string.IsNullOrEmpty (strUnZipPath)) {throw new ArgumentNullException (strUnZipPath) } try {var options = new ReadOptions {Encoding = Encoding.Default}; / / set encoding to solve Chinese garbled using (var zip = ZipFile.Read (strZipPath, options)) {foreach (var entry in zip) {if (string.IsNullOrEmpty (strUnZipPath)) {strUnZipPath = strZipPath.Split ('.'). First () } entry.Extract (strUnZipPath,overWrite? ExtractExistingFileAction.OverwriteSilently: ExtractExistingFileAction.DoNotOverwrite);} return true;}} catch (Exception ex) {throw new Exception (ex.Message);}}
3. Get the ZIP compressed stream object of the specified input stream:
/ get the ZIP compressed stream object of the specified input stream / entity name / public static Stream ZipCompress (Stream sourceStream, string entryName = "zip") {if (sourceStream = = null) {throw new ArgumentNullException ("sourceStream");} var compressedStream = new MemoryStream (); long sourceOldPosition = 0; try {sourceOldPosition = sourceStream.Position; sourceStream.Position = 0 Using (var zip = new ZipFile ()) {zip.AddEntry (entryName, sourceStream); zip.Save (compressedStream); compressedStream.Position = 0;} catch (Exception ex) {throw new Exception (ex.Message);} finally {try {sourceStream.Position = sourceOldPosition;} catch (Exception ex) {throw new Exception (ex.Message);}} return compressedStream;}
4. Get the ZIP decompressed stream object of the specified byte array:
/ get the ZIP decompression stream object of the specified byte array / the current method is only suitable for compressed files with only one compressed file, that is, only the first compressed file / public static Stream ZipDecompress (byte [] data) {Stream decompressedStream = new MemoryStream (); if (data = = null) return decompressedStream; try {var dataStream = new MemoryStream (data) in the method is fetched Using (var zip = ZipFile.Read (dataStream)) {if (zip.Entries.Count > 0) {zip.Entries.First () .Extract (decompressedStream); / / ms is operated in the Extract method. If you use it later, you must first return the Stream position to zero, otherwise it will cause no data to be read / / A position return action decompressedStream.Position = 0 before returning the Stream object. } catch (Exception ex) {throw new Exception (ex.Message);} return decompressedStream;} after reading the above, do you know how to use the .NET open source free ZIP library DotNetZip? If you want to learn more skills or want to know more about it, you are welcome to follow the industry information channel, thank you for reading!
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.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.