Details about the free and open-source. NET multi-type file extraction component SharpZipLib (. NET Component 7 ),

Source: Internet
Author: User

Details about the free and open-source. NET multi-type file extraction component SharpZipLib (. NET Component 7 ),

We have introduced six. NET components, one of which is File compression and decompression. Now we will introduce SharpZipLib, another file extraction component. In this component introduction series, you can simply introduce the background and simple application of the component. when reading this article, you can combine the introduction on the official website and local operations.

The related components are very powerful. in my introduction, I only mentioned simple applications. To learn more about the operations and features, please refer to the official website, you can also view the related classes and methods of the DLL file to expand the related business needs.

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

I. SharpZipLib component Overview:

Ziplib (SharpZipLib, formerly NZipLib) is a Zip, GZip, Tar, and BZip2 library fully written 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 ziplib creator said, "I have ported the zip library to C #. Because I need gzip/zip compression, I don't want to use libzip. dll or something similar I want all in pure C # ".

Download operations on the SharpZipLib Official Website :. NET 1.1 ,. NET 2.0 (3.5, 4.0 ),. net cf 1.0 ,. net cf 2.0 Assembly: Download 237 KB, download 708 kb for source code and examples; download 708 kb for source code and examples; download 1208 KB for help files;

SharpZipLib is released under GPL and complies with the Open Source protocol.

Ii. SharpZipLib core classes and methods:

The above briefly introduces the background of the SharpZipLib component. Now let's take a look at the 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 << 0x10);    }    else    {      this.WriteEncryptionHeader(entry.Crc);    }  }}

2. ZipOutputStream class Finish ():

public override void Finish(){  if (this.entries != null)  {    if (this.curEntry != null)    {      this.CloseEntry();    }    long count = this.entries.Count;    long sizeEntries = 0L;    foreach (ZipEntry entry in this.entries)    {      this.WriteLeInt(0x2014b50);      this.WriteLeShort(0x33);      this.WriteLeShort(entry.Version);      this.WriteLeShort(entry.Flags);      this.WriteLeShort((short) entry.CompressionMethodForHeader);      this.WriteLeInt((int) entry.DosTime);      this.WriteLeInt((int) entry.Crc);      if (entry.IsZip64Forced() || (entry.CompressedSize >= 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;  }}

Iii. SharpZipLib instance:

1. Compress a single file:

/// <Summary> /// compress a single file /// </summary> /// <param name = "fileToZip"> file to be compress </param> // /<param name = "zipedFile"> compressed file </param> // <param name = "compressionLevel"> compression level </param> // <param name = "blockSize"> size of each write </param> 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 ("specify the File to be compressed:" + fileToZip + "does not exist! ");} 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 );}}

2. Compress a single file:

/// <Summary> /// compress a single file /// </summary> /// <param name = "fileToZip"> name of the file to be compressed </param>/ // <param name = "zipedFile"> compressed file name </param> 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. compressing multi-layer directories:

/// <Summary> /// compress the multi-layer directory /// </summary> /// <param name = "strDirectory"> directory </param> /// <param name = "zipedFile"> compressed file </param> 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:

/// <Summary> /// recursively traverse the directory /// </summary> /// <param name = "strDirectory"> directory </param> /// <param name = "s"> ZipOutputStream object </param> // <param name = "parentPath"> parent path </param> 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 {// traverse all files and directories foreach (var file in filenames) {// first, it is processed as a Directory. if this Directory exists, recursively Copy the files under this 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 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. Decompress a zip file: 

/// <Summary> /// decompress a zip file. /// </Summary> /// <param name = "zipedFile"> The ziped file. </param> /// <param name = "strDirectory"> The STR directory. </param> // <param name = "password"> password of the zip file. </Param> /// <param name = "overWrite"> specifies whether to overWrite an existing file. </Param> 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. ge TCurrentDirectory ();} 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 );}}

Iv. Summary:

The above is an introduction to SharpZipLib components. This article is a simple introduction. If you need to learn more, you can go to the official website for details. The component functions are very powerful. How to Use components in the project to complete the functions we need to implement in the project is a requirement for every developer, we need to consider it carefully.

Any learning requires us to explore and think on our own. For a developer, the most important thing is thinking, because in our career, there is no importance beyond thinking. If you have any shortcomings, please include them and leave a message to correct them.

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.