C # Programming Summary (13) data compression
In the case of file storage or data transfer, data or files need to be compressed in order to save space traffic. Here we describe data compression through C #.
First, GZipStream compression
Microsoft provides a way to compress and decompress streams.
This class represents the GZIP data format, which uses the industry-standard algorithm for lossless compression and decompression of files. This format includes a cyclic redundancy check value for detecting data corruption. The GZIP data format uses the same algorithm as the Deflatestream class, but it can be extended to use other compression formats. This format can be easily implemented in a way that does not involve patent rights.
You can use a number of common compression tools to decompress a compressed GZipStream object that is written to a file with a. gz extension. However, this class does not originally provide the ability to add files to a. zip archive or extract files from a. zip archive.
The compression function in Deflatestream and GZipStream is exposed as a stream. Because the data is read in bytes, it is not possible to determine the best way to compress an entire file or a large chunk of data by making multiple passes. For uncompressed data sources, it is best to use the Deflatestream and GZipStream classes. If the source data is compressed, using these classes may actually increase the size of the stream.
Concrete realization of the source code
1. Compressed byte array
<summary>///Compressed byte array///</summary>//<param name= "str" ></param> ; public static byte[] Compress (byte[] inputbytes) {using (MemoryStream OutStream = new MemoryStream ( ) {using (GZipStream ZipStream = new GZipStream (OutStream, compressionmode.compress, True)) {zipstream.write (inputbytes, 0, inputbytes.length); Zipstream.close (); Important, must be closed, otherwise the return Outstream.toarray () cannot be extracted correctly; }}}///<summary>//Extract byte array///</summary>//<param Nam E= "str" ></param> public static byte[] Decompress (byte[] inputbytes) {using (Memorystrea M inputstream = new MemoryStream (inputbytes)) {using (MemoryStream OutStream = new MemoryStream ()) {using (gzipstrEAM zipStream = new GZipStream (InputStream, compressionmode.decompress)) {Zipst Ream. CopyTo (OutStream); Zipstream.close (); return Outstream.toarray (); } } } }2. Compressing strings
On the basis of the compressed bytes of the extension, note the character conversion, to ensure that there is no garbled. Specific principles, which are no longer described here, are visible:
C # Programming Summary (10) character transcoding http://www.cnblogs.com/yank/p/3536863.html
<summary>///compressed string///</summary>// <param name= "input" ></param> // <returns></returns> public static string Compress (string input) { byte[] inputbytes = Encoding.Default.GetBytes (input); Byte[] result = Compress (inputbytes); return convert.tobase64string (result); } <summary>//Extract strings////</summary>// <param name= "Input" ></param> //<returns></returns> public static string decompress (string input) { byte[] Inputbytes = convert.frombase64string (input); byte[] Depressbytes = decompress (inputbytes); Return Encoding.Default.GetString (depressbytes); }
3. Compress files
If you're trying to make a compression tool yourself, it works better than this method.
<summary>//Compressed catalogue///</summary>//<param name= "dir" ></param> public static void Compress (DirectoryInfo dir) {foreach (FileInfo filetocompress in dir. GetFiles ()) {Compress (filetocompress); }}///<summary>//Unzip the catalogue///</summary>//<param name= "dir" >< /param> public static void Decompress (DirectoryInfo dir) {foreach (FileInfo filetocompress in Dir. GetFiles ()) {decompress (filetocompress); }}///<summary>//Compressed files///</summary>//<param name= "Filetocompres S "></param> public static void Compress (FileInfo filetocompress) {using (FileStream ori Ginalfilestream = Filetocompress.openread ()) {if (File.getattributes (filetocompress.fulLName) & Fileattributes.hidden)! = Fileattributes.hidden & Filetocompress.extension! = ". Gz") { using (FileStream Compressedfilestream = file.create (Filetocompress.fullname + ". Gz")) {using (GZipStream Compressionstream = new GZipStream (Compressedfilestream, Compressionmode.compre ss)) {Originalfilestream.copyto (compressionstream); }}}}}//<summary>//Unzip the file/// </summary>//<param name= "filetodecompress" ></param> public static void decompress (Filei NFO filetodecompress) {using (FileStream Originalfilestream = Filetodecompress.openread ()) { string currentfilename = Filetodecompress.fullname; String newfilename = Currentfilename.remove (Currentfilename.lengTh-filetodecompress.extension.length); using (FileStream Decompressedfilestream = File.create (NewFileName)) {using (GZipStream Decompressionstream = new GZipStream (Originalfilestream, compressionmode.decompress)) { Decompressionstream.copyto (Decompressedfilestream); } } } }
Second, open source component Icsharpcode.sharpziplib to compress
Icsharpcode.sharpziplib, open source components, support Zip,gzip,bzip2,tar, etc.
Its compression efficiency and compression compared to the Microsoft comes with better. and provide the source code, open source for its algorithm research, improvement. Specifically visible:
http://www.icsharpcode.net/OpenSource/SharpZipLib/
Here is a simple implementation for reference, other algorithms are similar, no longer repeat.
1. Using BZIP2 to compress strings
<summary>//Compression///</summary>//<param name= "input" ></param> <returns></returns> public static string Compress (String input) {string R Esult = string. Empty; byte[] buffer = Encoding.UTF8.GetBytes (input); using (MemoryStream outputstream = new MemoryStream ()) {using (Bzip2outputstream ZipStream = NE W Bzip2outputstream (OutputStream)) {zipstream.write (buffer, 0, buffer. Length); Zipstream.close (); } return Convert.tobase64string (Outputstream.toarray ()); }}///<summary>//Unzip//</summary>//<param name= "input" >< /param>//<returns></returns> public static string decompress (string input) { string result = String. Empty; Byte[] buffer = convert.frombase64string (input); using (Stream InputStream = new MemoryStream (buffer)) {Bzip2inputstream ZipStream = new bzip2in Putstream (InputStream); using (StreamReader reader = new StreamReader (ZipStream, Encoding.UTF8)) {//output result = reader. ReadToEnd (); }} return result; }Third, Demo
Http://files.cnblogs.com/yank/CompressSample.zip
Iv. Follow-up
If there are other better compression methods, please indicate. Subsequent updates are updated to this point.
C # Programming Summary (13) data compression