Dotnet Ultimate Compression

Source: Internet
Author: User
Tags dotnet

In fact, there is nothing that is the ultimate, just an eye-catching title. CLR2.0 brings a lot of new things, including System. IO. compression is a new namespace, which includes two classes: GzipStream and DeflaterStream. They can be used for decompression, but do not support common compressed files such as ZIP and RAR, RAR is a patent-related issue. Although the ZIP format is public, I think Microsoft does not want to support it. It may want to use its own Private Kitchen CAB format, but Dotnet CLR does not support it, so we despise it!

There are a lot of posts on the Internet about how to decompress, but there is little comprehensive introduction, or there are bugs in the code. Users on CSDN also asked this question a lot, but there is no standard answer. I am sending out the recently written compressed code, which is a standard answer for everyone.

The following are the codes of the two classes that belong to the space of ExpertLib. Compress. They are

Compress (ExpertLib. Compress. Compress) // multiple common compression functions implemented using GzipStream

ZIP (ExpertLib. Compress. ZIP) // a standard ZIP file that can be packaged and decompressed.

 

Code support:

First, you need to run this code on CLR2.0, because GzipStream is provided only in 2.0, and there is no reason why I don't use DeflaterStream!

In addition, if you use the ZIP class to decompress the ZIP file, please download the latest SharpZipLib (: http://www.icsharpcode.net/OpenSource/SharpZipLib/Download.aspx) Here, of course you also need the for2.0 version, you can go to the source code of this address. You can look at the source code.

Note:

I have provided the ToBase64String and FromBase64String methods in the Compress class. This encoding method can be implemented through the firewall when data is transmitted over HTTP.

BUG report:

The FastZip class is used in the implementation of ZIP, but FastZip does not seem to support PassWord, or I am useless.
---------------------------------------------- I am a separation line --------------------------------------------

Using System;
Using System. Collections. Generic;
Using System. Text;
Using System. IO;
Using System. IO. Compression;
Using System. Xml;
Using System. Data;
Using System. Runtime. Serialization. Formatters. Binary;

Namespace Streaming. Compress
{
/// <Summary>
/// Compression class. Only CLR 2.0 is supported. The GZipStream class added by. 0 is used.
/// </Summary>
Public class Compress
{

# Region Compression

# Region CompressXmlDocument
/// <Summary>
/// Compress an XML document
/// </Summary>
/// <Param name = "input"> The XML document to compress. </param>
/// <Returns> Returns the compressed XML document. </returns>
Public static byte [] CompressXmlDocument (XmlDocument input)
{
Return CompressString (input. InnerXml );
}
# Endregion

# Region CompressDataSet
/// <Summary>
/// Compress DataSet
/// </Summary>
/// <Param name = "input"> The DataSet to compress. </param>
/// <Returns> Returns the compressed DataSet. </returns>
Public static byte [] CompressDataSet (DataSet input)
{
BinaryFormatter bf = new BinaryFormatter ();

Using (MemoryStream MS = new MemoryStream ())
{
Bf. Serialize (MS, input );
Return CompressBytes (ms. GetBuffer ());
}
}
# Endregion

# Region CompressString
/// <Summary>
/// Compress the string
/// </Summary>
/// <Param name = "unCompressedString"> </param>
/// <Returns> </returns>
Public static byte [] CompressString (string unCompressedString)
{
Byte [] bytData = System. Text. Encoding. UTF8.GetBytes (unCompressedString );
Return CompressBytes (bytData );
}
# Endregion CompressString

# Region CompressBytes

/// <Summary>
/// Compress the byte array
/// </Summary>
Public static byte [] CompressBytes (byte [] data)
{
MemoryStream output = new MemoryStream ();
GZipStream gzip = new GZipStream (output,
CompressionMode. Compress, true );
Gzip. Write (data, 0, data. Length );
Gzip. Close ();
Return output. ToArray ();
}
# Endregion

# Endregion

# Region Decompression

# Region DecompressXmlDocument
/// <Summary>
/// Decompress the Byte array generated by CompressXmlDocument
/// </Summary>
/// <Param name = "input"> The buffer that contains the compressed
/// Stream with the XML document. </param>
/// <Returns> Returns the decompressed XML document. </returns>
Public static XmlDocument DecompressXmlDocument (byte [] input)
{
XmlDocument doc = new XmlDocument ();
Doc. LoadXml (DecompressString (input ));
Return doc;
}

# Endregion

# Region DecompresString
/// <Summary>
/// Extract the string generated by CompressString Compression
/// </Summary>
/// <Param name = "data"> </param>
/// <Returns> </returns>
Public static string DecompressString (byte [] data)
{
Return System. Text. Encoding. UTF8.GetString (DecompressBytes (data ));
}

# Endregion

# Region DecompressDataSet

/// <Summary>
/// Decompress the Byte array generated by CompressDataSet
/// </Summary>
/// <Param name = "input"> The buffer that contains the compressed
/// Stream with the DataSet. </param>
/// <Returns> Returns the decompressed DataSet. </returns>
Public static DataSet DecompressDataSet (byte [] input)
{
BinaryFormatter bf = new BinaryFormatter ();

Byte [] buffer = DecompressBytes (input );
Using (MemoryStream MS = new MemoryStream (buffer ))
{
Return (DataSet) bf. Deserialize (MS );
}
}

# Endregion

# Region DecompressBytes

/// <Summary>
/// Extract the byte array
/// </Summary>
/// <Param name = "data"> The buffer that contains the compressed
/// Stream with the bytes. </param>
/// <Returns> Returns the decompressed bytes. </returns>
Public static byte [] DecompressBytes (byte [] data)
{

MemoryStream input = new MemoryStream ();
Input. Write (data, 0, data. Length );
Input. Position = 0;
GZipStream gzip = new GZipStream (input, CompressionMode. Decompress, true );

MemoryStream output = new MemoryStream ();
Byte [] buff = new byte [4096];
Int read =-1;
Read = gzip. Read (buff, 0, buff. Length );
While (read> 0)
{
Output. Write (buff, 0, read );
Read = gzip. Read (buff, 0, buff. Length );
}
Gzip. Close ();
Return output. ToArray ();
}

# Endregion

# Endregion

 

# Region auxiliary functions
# Region ToBase64String
/// <Summary>
/// Convert to a Base64 encoded string that can be transmitted online
/// </Summary>
Public static string ToBase64String (byte [] data)
{
Return Convert. ToBase64String (data );
}
# Endregion

# Region FromBase64String
/// <Summary>
/// Convert a Base64 encoded string to a byte array
/// </Summary>
Public static byte [] FromBase64String (string str)
{
Return Convert. FromBase64String (str );
}

# Endregion

# Endregion

}
}

---------------------------------------------- I am a separation line --------------------------------------------

Using System;
Using System. Collections. Generic;
Using System. Text;
Using System. IO;
Using ICSharpCode. SharpZipLib;
Using ICSharpCode. SharpZipLib. Core;
Using ICSharpCode. SharpZipLib. Zip;

Namespace Streaming. Compress
{
# Region Delegation
Public class ZipProcessEventArgs: System. EventArgs
{
Public string Name;
Public bool ContinueRunning;
/// <Summary>
/// File or directory; false indicates file; true indicates directory
/// </Summary>
Public bool FileOrDirectory;
}
Public delegate void ZipProcessEventDelegate (object sender, ZipProcessEventArgs e );
# Endregion

/// <Summary>
/// ZIP file decompression class
/// </Summary>
Public class ZIP
{
# Region internal variables
Private FastZipEvents events;
Private FastZip fz;
# Endregion

# Region Constructor
Public ZIP ()
{
Events = new FastZipEvents ();
Events. ProcessDirectory = new ProcessDirectoryHandler (OnProcessDirectory );
Events. ProcessFile = new ProcessFileHandler (OnProcessFile );
Fz = new FastZip (events );
}
# Endregion

# Region Event
/// <Summary>
/// File Processing
/// </Summary>
Public event ZipProcessEventDelegate ProcessFileEvent;
/// <Summary>
/// Directory Processing
/// </Summary>
Public event ZipProcessEventDelegate ProcessDirectoryEvent;
# Endregion

# Region private Method
Private void OnProcessFile (object sender, ScanEventArgs e)
{
If (this. ProcessFileEvent! = Null)
{
ZipProcessEventArgs ea = new ZipProcessEventArgs ();
Ea. Name = e. Name;
Ea. ContinueRunning = true;
Ea. FileOrDirectory = false;
This. ProcessFileEvent (this, ea );
E. ContinueRunning = ea. ContinueRunning;
}
}

Private void OnProcessDirectory (object sender, DirectoryEventArgs e)
{
If (this. ProcessDirectoryEvent! = Null)
{
ZipProcessEventArgs ea = new ZipProcessEventArgs ();
Ea. Name = e. Name;
Ea. ContinueRunning = true;
Ea. FileOrDirectory = true;
This. ProcessDirectoryEvent (this, ea );
E. ContinueRunning = ea. ContinueRunning;
}
}
# Endregion

# Region ZipDirectory
/// <Summary>
/// Compress all the files in a directory into a Zip package
/// </Summary>
/// <Param name = "zipFilename"> compressed file name </param>
/// <Param name = "sourceDirectory"> directory of the file to be compressed </param>
Public void ZipDirectory (string zipFile, string sourceDirectory)
{
ZipDirectory (zipFile, sourceDirectory, null );
}
/// <Summary>
/// Compress all the files in a directory into a Zip package
/// </Summary>
Public void ZipDirectory (string zipFile, string sourceDirectory, string password)
{
If (zipFile = null) | (zipFile. Trim () = ""))
{
Throw new System. ArgumentNullException ("zipFile ");
}

If (sourceDirectory = null) | (sourceDirectory. Trim () = ""))
{
Throw new System. ArgumentNullException ("sourceDirectory ");
}

If (! Directory. Exists (sourceDirectory ))
{
Throw new System. Exception ("No Exists Directory! ");
}

If (password = null) | (password = ""))
{
Fz. Password = null;
}
Else
{
Fz. Password = password;
}

Fz. CreateZip (zipFile, sourceDirectory, true, null );
Fz. Password = null;
}
# Endregion

# Region UnzipDirectory
/// <Summary>
/// Decompress a zip file to a directory
/// </Summary>
/// <Param name = "zipFile"> files to be decompressed </param>
/// <Param name = "directory"> directory of the decompressed file </param>
Public void UnzipDirectory (string zipFile, string directory)
{
UnzipDirectory (zipFile, directory, null );
}

/// <Summary>
/// Decompress a zip file to a directory
/// </Summary>
Public void UnzipDirectory (string zipFile, string directory, string password)
{
If (zipFile = null) | (zipFile. Trim () = ""))
{
Throw new System. ArgumentNullException ("zipFile ");
}

If (directory = null) | (directory. Trim () = ""))
{
Throw new System. ArgumentNullException ("sourceDirectory ");
}

If (! File. Exists (zipFile ))
{
Throw new System. Exception ("No Exists Zip file:" + zipFile );
}

If (! Directory. Exists (directory ))
Directory. CreateDirectory (directory );

If (password = null) | (password = ""))
{
Fz. Password = null;
}
Else
{
Fz. Password = password;
}

Fz. ExtractZip (zipFile, directory, null );
Fz. Password = null;
}
# Endregion
}
}

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.