Sharpziplib is an open-source zip, Gzip, tar, and Bzip2 library written in C #. It can be obtained at http://www.icsharpcode.net/opensource/sharpziplib.
Compression
For convenience, we add Io, text, and sharpziplib namespaces. Using system;
Using system. IO;
Using system. text;
Using icsharpcode. sharpziplib. Bzip2;
First, Start compression. We create a memorystream Memorystream mscompressed = new memorystream ();
This time I use Bzip2 and you can use ZIP or tar. However, they need to implement a false file. selecting Bzip2 instead of Gzip is because big data will be smaller. at the cost of a large header.
Next, we will create a Bzip2 output stream object to accommodate memorystream.
Bzip2outputstream zoscompressed =NewBzip2outputstream (mscompressed );
Now let me explain the meaning of the above header. in my actual test, when using gzip, compressing 1 byte of data requires 28 bytes of additional header, which cannot be compressed. when Bzip2 is used, an additional 36-byte header is required. in fact, Bzip2 can be used to compress a 12892-byte source file to 2563 bytes, with a compression rate of about 75%. another test is to compress 730 bytes to 429 bytes, And the last test is 174 bytes to 161 bytes. obviously, any compression requires additional space available.
Below we write data into bzip2outputstream String sbuffer = "this represents some data being compressed ."
Byte [] bytesbuffer = encoding. ASCII. getbytes (sbuffer );
Zoscompressed. Write (bytesbuffer, 0, bytesbuffer. Length );
Zoscompressed. Finalize ();
Zoscompressed. Close ();
Because I/O and stream methods are used, byte arrays must be used to replace strings. Therefore, we use byte arrays as the output and then write the compressed stream into the memory stream. Bytesbuffer = mscompressed. toarray ();
String scompressed = encoding. ASCII. getstring (bytesbuffer );
In this way, the memory stream contains compressed data, which is output in a character array and then converted to a string. note that this string is garbled and unreadable. if you want to view the data, I use the method to convert it to base64 encoded data, but this will increase the size. run the program to convert 43 bytes of uncompressed data into 74 bytes of compressed data. If you use Base 64 encoding, the result will be 100 bytes:
Qlpootfbwsztwzxkipsaaamtgeabbaa + 49 waiaaxttixmteimjhnndibvq
Awyyehiwn49ldoknqkn2c9zug5 + luskckehomhfng =
Extract Memorystream msuncompressed =
New memorystream (encoding. ASCII. getbytes (scompressed ));
Bzip2inputstream zisuncompressed = new bzip2inputstream (msuncompressed );
Bytesbuffer = new byte [zisuncompressed. Length];
Zisuncompressed. Read (bytesbuffer, 0, bytesbuffer. Length );
Zisuncompressed. Close ();
Msuncompressed. Close ();
String suncompressed = encoding. ASCII. getstring (bytesbuffer );
In this way, suncompressed will be decompressed to the original string. The file is also the same principle. Created by jecray