C# GZipStream Read

Description

GZipStream Read Reads a number of decompressed bytes into the specified byte array.

Syntax

GZipStream.Read has the following syntax.


public override int Read(
  byte[] array,/* w  w  w .  ja  v a 2s.  com*/
  int offset,
  int count
)

Parameters

GZipStream.Read has the following parameters.

  • array - The array used to store decompressed bytes.
  • offset - The byte offset in array at which the read bytes will be placed.
  • count - The maximum number of decompressed bytes to read.

Returns

GZipStream.Read method returns The number of bytes that were decompressed into the byte array. If the end of the stream has been reached, zero or the number of bytes read is returned.

Example

The following example shows how to compress and decompress bytes by using the Read and Write methods.


/*from  w  ww  .  j  a  va2s.c om*/
using System;
using System.Text;
using System.IO;
using System.IO.Compression;

class Program
{
    static void Main(string[] args)
    {
        UnicodeEncoding uniEncode = new UnicodeEncoding();

        byte[] bytesToCompress = uniEncode.GetBytes("example text to compress and decompress");
        Console.WriteLine("starting with: " + uniEncode.GetString(bytesToCompress));

        using (FileStream fileToCompress = File.Create("examplefile.gz"))
        {
            using (GZipStream compressionStream = new GZipStream(fileToCompress, CompressionMode.Compress))
            {
                compressionStream.Write(bytesToCompress, 0, bytesToCompress.Length);
            }
        }

        byte[] decompressedBytes = new byte[bytesToCompress.Length];
        using (FileStream fileToDecompress = File.Open("examplefile.gz", FileMode.Open))
        {
            using (GZipStream decompressionStream = new GZipStream(fileToDecompress, CompressionMode.Decompress))
            {
                decompressionStream.Read(decompressedBytes, 0, bytesToCompress.Length);
            }
        }

        Console.WriteLine("ending with: " + uniEncode.GetString(decompressedBytes));
    }
}

The code above generates the following result.





















Home »
  C# Tutorial »
    System.IO.Compression »




DeflateStream
GZipStream
ZipArchive
ZipArchiveEntry
ZipFile
ZipFileExtensions