Книга: C# 2008 Programmer

Compression

Compression

The compression classes read data (to be compressed) from a byte array, compress it, and store the results in a Stream object. For decompression, the compressed data stored in a Stream object is decompressed and then stored in another Stream object.

Let's see how you can perform compression. First, define the Compress() function, which takes in two parameters: algo and data. The first parameter specifies which algorithm to use (GZip or Deflate), and the second parameter is a byte array that contains the data to compress. A MemoryStream object will be used to store the compressed data. The compressed data stored in the MemoryStream is then copied into another byte array and returned to the calling function. The Compress() function is defined as follows:

static byte[] Compress(string algo, byte[] data) {
 try {
  //---the ms is used for storing the compressed data---
  MemoryStream ms = new MemoryStream();
  Stream zipStream = null;
  switch (algo) {
  case "Gzip":
   zipStream =
    new GZipStream(ms, CompressionMode.Compress, true);
   break;
  case "Deflat":
   zipStream =
    new DeflateStream(ms, CompressionMode.Compress, true);
   break;
  default:
   return null;
  }
  //---compress the data stored in the data byte array---
  zipStream.Write(data, 0, data.Length);
  zipStream.Close();
  //---store the compressed data into a byte array---
  ms.Position = 0;
  byte[] c_data = new byte[ms.Length];
  //---read the content of the memory stream into the byte array---
  ms.Read(c_data, 0, (int)ms.Length);
  return c_data;
 } catch (Exception ex) {
  Console.WriteLine(ex.ToString());
  return null;
 }
}

Оглавление книги

Оглавление статьи/книги

Генерация: 0.035. Запросов К БД/Cache: 0 / 0
поделиться
Вверх Вниз