Compressed text, byte, or file compression helper class-gziphelper Welcome collection
Here is a brief introduction to you. NET auxiliary public class Gziphelper, the main function of the tool class is to compress and decompress text, characters, files, etc. This class is implemented primarily using namespaces: The GZipStream class under System.IO.Compression. 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. The format of gzip can be from the RFC 1952 "gzip file format specification 4.3 (gzip file formats specification 4.3) gzip files format Specification 4.3 (gzip document formats Specification 4.3 ) "is obtained in. This class cannot be used to compress files that are larger than 4 GB.
First, the attribute
BaseStreamGets a reference to the underlying stream.
CanReadGets a value that indicates whether the stream supports reading files during the decompression of a file. (Rewrite Stream ...::.) CanRead. )
CanSeekGets a value that indicates whether the stream supports lookups. (Rewrite Stream ...::.) CanSeek. )
CantimeoutGets a value that determines whether the current stream can time out. (Inherit from Stream.) )
CanWriteGets a value that indicates whether the stream supports writing. (Rewrite Stream ...::.) CanWrite. )
LengthNot supported, and always throws NotSupportedException. (Rewrite Stream ...::.) Length. )
PositionNot supported, and always throws NotSupportedException. (Rewrite Stream ...::.) Position. )
ReadTimeoutGets or sets a value, in milliseconds, that determines how long the stream attempts to read before timing out. (Inherit from Stream.) )
WriteTimeoutGets or sets a value, in milliseconds, that determines how long the stream attempts to write before timing out. (Inherit from Stream.) )
Second, the method
BeginReadBegins an asynchronous read operation. (Rewrite Stream ...::.) BeginRead (array<byte>[] () [], Int32, Int32, AsyncCallback, Object). )
BeginWriteBegins an asynchronous write operation. (Rewrite Stream ...::.) BeginWrite (array<byte>[] () [], Int32, Int32, AsyncCallback, Object). )
CloseCloses the current stream and frees all resources associated with it (such as sockets and file handles). (Inherit from Stream.) )
CreateobjrefCreates an object that contains all the relevant information required to generate a proxy for communicating with a remote object. (inherited from MarshalByRefObject.) )
Disposeis overloaded.
EndReadWaits for the pending asynchronous read to complete. (Rewrite Stream ...::.) EndRead (IAsyncResult). )
EndWriteHandles the end of an asynchronous write. (Rewrite Stream ...::.) EndWrite (IAsyncResult). )
FlushFlushes the contents of the internal buffer of the current GZipStream object to the underlying stream. (Rewrite Stream ...::.) Flush () () () (). )
GetHashCodeServes as a hash function for a particular type. (Inherit from Object.) )
GetlifetimeserviceRetrieves the current lifetime service object that controls the lifetime policy of this instance. (inherited from MarshalByRefObject.) )
InitializeLifetimeServiceGets the lifetime service object that controls the lifetime policy for this instance. (inherited from MarshalByRefObject.) )
MemberwiseCloneis overloaded.
ReadReads a number of decompressed bytes into the specified byte array. (Rewrite Stream ...::.) Read (array<byte>[] () [], Int32, Int32). )
ReadByteReads a byte from the stream and advances the position within the stream by one byte, or returns 1 if the end of the stream has been reached. (Inherit from Stream.) )
SeekThis property is not supported and always throws NotSupportedException. (Rewrite Stream ...::.) Seek (Int64, SeekOrigin). )
SetLengthThis property is not supported and always throws NotSupportedException. (Rewrite Stream ...::.) SetLength (Int64). )
WriteWrites the compressed bytes from the specified byte array to the underlying stream. (Rewrite Stream ...::.) Write (array<byte>[] () [], Int32, Int32). )
WriteByteWrites a byte to the current position within the stream and advances the position within the stream by one byte. (Inherit from Stream.) )
To compress the extracted file instance code using native methods:
<summary>///ZIP file///</summary>/<param name= "filename" > file name (full path) </param>// <param name= "Data" > string required for compression </param> public void Compressfile (string fileName, string data) { FileStream fstream = new FileStream (FileName, FileMode.Create, FileAccess.Write); GZipStream gstream = new GZipStream (fstream, compressionmode.compress); StreamWriter swriter = new StreamWriter (gstream); Swriter. Write (data); Swriter. Close (); Gstream. Close (); FStream. Close (); }
<summary>//Unzip///</summary>//<param name= "filename" > file name (full path) </param>/// Lt;returns></returns> public string Decompressfile (string fileName) {string cstring= ""; FileStream fstream = new FileStream (FileName, FileMode.Open, FileAccess.Read); GZipStream gstream = new GZipStream (fstream, compressionmode.decompress); StreamReader reader = new StreamReader (gstream); Cstring=reader. ReadToEnd (); Reader. Close (); Gstream. Close (); FStream. Close (); return CString; }
Gziphelper public class is the encapsulation of common decompression based on the GZipStream class. The Gziphelper class diagram looks like this:
Gziphelper public class full Source:
Using system;using system.io;using system.io.compression;using system.text;namespace RDIFramework.Utilities{//< summary>///Compressed text, byte, or file Compression helper class///</summary> public class Gziphelper {//<summary> Compressed strings///</summary>//<param name= "text" ></param>//<RETURNS>&L t;/returns> public static string Compress (string text) {//Convert text to bytes b yte[] 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" >&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[] WR Itedata = new byte[4096]; T ms = default (t); using (Stream sg = new GZipStream (stream, mode)) {while (true) {ARR Ay. 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" ></param>//<returns></returns> public static byte[] Decompress (byte[] bytdata) {using (MemoryStream stream = gzip<memorystream& gt; (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.filedel (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 (); } } } }}
Resources
MSDN GZipStream Class Introduction
Compressed text, byte, or file compression helper class-gziphelper Welcome collection