Compression helper class for compressing text, bytes, or files

Source: Internet
Author: User

Using system;using system.collections.generic;using system.text;using system.diagnostics;using System.IO;using Microsoft.win32;using system.io.compression;using System.runtime.serialization.formatters.binary;namespace        aimscommon{//<summary>//Compressed text, byte or file compression helper class///</summary> public class Gziphelper {        <summary>///Compressed strings///</summary>//<param name= "text" ></param> <returns></returns> public static string Compress (string text) {//Convert Tex            T to bytes byte[] buffer = Encoding.UTF8.GetBytes (text);            Get a stream MemoryStream ms = new MemoryStream ();            Get ready-to-zip up our stream using (GZipStream zip = new GZipStream (MS, Compressionmode.compress, true)) {//compress the data into our buffer zip. Write (buffer, 0, buffer.            Length);           } Reset our position in compressed stream to the start Ms.            Position = 0; Get the compressed data byte[] Compressed = Ms.            ToArray (); Ms. Read (compressed, 0, compressed.            Length); Prepare final data with header that indicates length byte[] gzbuffer = new byte[compressed.            Length + 4]; Copy compressed data 4 bytes from start of final header System.Buffer.BlockCopy (compressed, 0, Gzbuffer, 4, C Ompressed.            Length); Copy header to first 4 bytes System.Buffer.BlockCopy (bitconverter.getbytes (Buffer.            Length), 0, Gzbuffer, 0, 4);        Convert back to string and return return convert.tobase64string (Gzbuffer); }///<summary>//Extract strings///</summary>//<param name= "Compressedtext" &GT;&L        t;/param>//<returns></returns> public static string uncompress (String compressedtext)      {      Get string as bytes byte[] Gzbuffer = convert.frombase64string (Compressedtext);            Prepare stream to do uncompression MemoryStream ms = new MemoryStream ();            Get the length of compressed data int msglength = Bitconverter.toint32 (gzbuffer, 0); Uncompress everything besides the header Ms.            Write (Gzbuffer, 4, gzbuffer.length-4);            Prepare final buffer for just uncompressed data byte[] buffer = new Byte[msglength]; Reset our position on stream since we ' re starting over Ms.            Position = 0;            Unzip the data through stream gzipstream zip = new GZipStream (MS, compressionmode.decompress); Do the unzip zip. Read (buffer, 0, buffer.            Length);        Convert back to string and return return Encoding.UTF8.GetString (buffer); } public static T gzip<t> (stream stream, Compressionmode mode) where T:stream {byte[] writedata = new byte[4096];            T ms = default (t);                    using (Stream sg = new GZipStream (stream, mode)) {while (true) {                    Array.clear (writedata, 0, writedata.length); int size = sg.                    Read (writedata, 0, writedata.length); if (Size > 0) {Ms.                    Write (writedata, 0, size);                    } else {break;            }} return MS; }}///<summary>//Compressed Bytes///</summary>//<param name= "Bytdata" >&            lt;/param>//<returns></returns> public static byte[] Compress (byte[] bytdata) {    using (MemoryStream stream = gzip<memorystream> (new MemoryStream (Bytdata), compressionmode.compress))        {return stream.            ToArray (); }}///<summary>//Extract bytes///</summary>//<param name= "Bytdata" >&            lt;/param>//<returns></returns> public static byte[] Decompress (byte[] bytdata) {            using (MemoryStream stream = gzip<memorystream> (new MemoryStream (Bytdata), compressionmode.decompress)) {return stream.            ToArray (); }}///<summary>//Compressed file///</summary>//<param name= "SourceFile" &G t; source file </param>///<param Name= "destinationfile" > destination file </param> public static void Compressfi                Le (String sourcefile, String destinationfile) {if (file.exists (sourcefile) = = false)//determine if the file exists            throw new FileNotFoundException (); if (file.exists (destinationfile) = = false)//determine if the target file file exists Filehelper.deletefIle (Destinationfile);            Create file stream and byte array byte[] buffer = NULL;            FileStream sourcestream = null;            FileStream destinationstream = null;            GZipStream compressedstream = null;                 try {sourcestream = new FileStream (sourcefile, FileMode.Open, FileAccess.Read, FileShare.Read);                Buffer = new Byte[sourcestream.length]; Store the file stream into a byte array of int checkcounter = sourcestream.read (buffer, 0, buffer.                Length); if (checkcounter! = buffer.                Length) {throw new ApplicationException ();                } Destinationstream = new FileStream (Destinationfile, FileMode.OpenOrCreate, FileAccess.Write); Create GZipStream instance, write compressed file stream compressedstream = new GZipStream (Destinationstream, Compressionmode.compres                s, true); Compressedstream.write (buffer, 0, buffer.)            Length); } finally           {//Make sure we allways close all streams if (sourcestream! = null)                {Sourcestream.close ();}                if (compressedstream! = null) {Compressedstream.close ();}            if (destinationstream! = null) {Destinationstream.close ();} }}///<summary>//Unzip the file///</summary>//<param name= "SourceFile" &G t; source file </param>///<param Name= "destinationfile" > destination file </param> public static void decompress File (String sourcefile, String destinationfile) {if (!            File.exists (sourcefile)) {throw new FileNotFoundException ();            } FileStream stream = null;            FileStream stream2 = null;            GZipStream stream3 = null;            byte[] buffer = NULL; try {stream = new FileStream (sourcefile, Filemode.open);                STREAM3 = new GZipStream (stream, compressionmode.decompress, true);                Buffer = new BYTE[4]; int num = ((int) stream.                Length)-4; Stream.                Position = num; Stream.                Read (buffer, 0, 4); Stream.                Position = 0L;                byte[] Buffer2 = new Byte[bitconverter.toint32 (buffer, 0) + 100];                int offset = 0;                int count = 0; while (true) {int num5 = stream3.                    Read (buffer2, offset, 100);                    if (NUM5 = = 0) {break;                    } offset + = NUM5;                Count + = NUM5;                } stream2 = new FileStream (destinationfile, FileMode.Create); Stream2.                Write (buffer2, 0, Count); Stream2.            Flush ();           } finally {if (stream! = null) {         Stream.                Close (); } if (stream3! = null) {stream3.                Close (); } if (stream2! = null) {stream2.                Close (); }            }        }    }}

Compression helper class for compressing text, bytes, or files

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.