C # programming Summary (13) Data Compression

Source: Internet
Author: User

Data or files must be compressed to save space traffic during file storage or data transmission. Here we will describe how to compress data through C. 1. GZipStream compression Microsoft provides methods for compressing and extracting streams. This class represents the GZip data format, which uses industry-standard algorithms for lossless compression and decompression of files. This format includes a cyclic redundancy check value that detects data corruption. GZip uses the same algorithm as DeflateStream, but it can be extended to use other compression formats. This format can be easily implemented in a way that does not involve the right to use a patent. You can use many common compression tools to write data to a file with the extension. gz files are compressed GZipStream objects for decompression; however, such files are not provided. add files in the zip file or. extract files in the zip archive. The compression functions in DeflateStream and GZipStream are made public as streams. Because the data is read in byte mode, it is impossible to determine the best way to compress the entire file or large data block by multiple transfers. DeflateStream and GZipStream are recommended for uncompressed data sources. If the source data is compressed, the stream size may increase when these classes are used. Specific implementation source code 1. Copy the compressed byte array code /// <summary> /// compress the 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 (); // very important. It must be closed; otherwise, return outStream cannot be decompressed correctly. toArr Ay ();}}} /// <summary> /// extract the byte array /// </summary> /// <param name = "str"> </param> public static byte [] Decompress (byte [] inputBytes) {using (MemoryStream inputStream = new MemoryStream (inputBytes) {using (MemoryStream outStream = new MemoryStream () {using (GZipStream zipStream = new GZipStream (inputStream, CompressionMode. decompress) {zipStream. copyTo (outStream); zipStream. close (); return OutStream. ToArray () ;}}} copy code 2. Compress strings based on the size of compressed bytes. Note character conversion to avoid garbled characters. The specific principle is not introduced here. It can be seen that: C # programming Summary (10) character transcoding http://www.cnblogs.com/yank/p/3536863.html copy code /// <summary> /// compress the 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 the string /// </summary> /// <par Am 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);} copy code 3. compress the file. If you try to compress the file by yourself, this method is useful in copying code /// <summary> /// compress the directory /// </summary> /// <param name = "dir"> </param> public static void Compress (DirectoryInfo di R) {foreach (FileInfo fileToCompress in dir. getFiles () {Compress (fileToCompress );}} /// <summary> /// extract the directory /// </summary> /// <param name = "dir"> </param> public static void Decompress (DirectoryInfo dir) {foreach (FileInfo fileToCompress in dir. getFiles () {Decompress (fileToCompress );}} /// <summary> /// compressed file /// </summary> /// <param name = "fileToCompress"> </param> public static void Compr Ess (FileInfo fileToCompress) {using (FileStream originalFileStream = 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. compress) {originalFileStream. copyTo (compressionStream );}}}}} /// <summary> /// Decompress the file /// </summary> /// <param name = "fileToDecompress"> </param> public static void Decompress (FileInfo 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) ;}}} copy code 2. Open-source component ICSharpCode. sharpZipLib compresses ICSharpCode. sharpZipLib is an open-source component that supports Zip, GZip, BZip2, and Tar. Its compression efficiency and compression ratio are better than those of Microsoft. It also provides the source code and open source code to study and improve its algorithms. Specific visible: http://www.icsharpcode.net/OpenSource/SharpZipLib/ here provides a simple implementation for reference, other algorithms are similar, no more details. 1. Use BZip2 to compress the string and copy the code /// <summary> /// compression /// </summary> /// <param name = "input"> </param> /// <returns> </returns> public static string Compress (string input) {string result = string. empty; byte [] buffer = Encoding. UTF8.GetBytes (input); using (MemoryStream outputStream = new MemoryStream () {using (BZip2OutputStream zipStream = new BZip2OutputStream (outputStream) {zipStream. write (buffer, 0, buffer. length); zipStream. close ();} return Convert. toBase64String (outputStream. toArray ());}} /// <summary> /// extract /// </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 BZip2InputStream (inputStream); using (StreamReader reader = new StreamReader (zipStream, Encoding. UTF8) {// output result = reader. readToEnd () ;}} return result ;}

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.