C# DeflateStream Write

Description

DeflateStream Write Writes compressed bytes to the underlying stream from the specified byte array.

Syntax

DeflateStream.Write has the following syntax.


public override void Write(
  byte[] array,//from ww w. j a v  a2 s  .c  om
  int offset,
  int count
)

Parameters

DeflateStream.Write has the following parameters.

  • array - The buffer that contains the data to compress.
  • offset - The byte offset in array from which the bytes will be read.
  • count - The maximum number of bytes to write.

Returns

DeflateStream.Write method returns

Example

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


//from w ww .jav a 2s  . c o  m

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 (DeflateStream compressionStream = new DeflateStream(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 (DeflateStream decompressionStream = new DeflateStream(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