Ionic.Zlib.GZipStream.Write C# (CSharp) Method

Write() public method

Write data to the stream.

If you wish to use the GZipStream to compress data while writing, you can create a GZipStream with CompressionMode.Compress, and a writable output stream. Then call Write() on that GZipStream, providing uncompressed data as input. The data sent to the output stream will be the compressed form of the data written.

A GZipStream can be used for Read() or Write(), but not both. Writing implies compression. Reading implies decompression.

public Write ( byte buffer, int offset, int count ) : void
buffer byte The buffer holding data to write to the stream.
offset int the offset within that data array to find the first byte to write.
count int the number of bytes to write.
return void
        public override void Write(byte[] buffer, int offset, int count)
        {
            if (_disposed) throw new ObjectDisposedException("GZipStream");
            if (_baseStream._streamMode == Ionic.Zlib.ZlibBaseStream.StreamMode.Undefined)
            {
                //Console.WriteLine("GZipStream: First write");
                if (_baseStream._wantCompress)
                {
                    // first write in compression, therefore, emit the GZIP header
                    _headerByteCount = EmitHeader();
                }
                else
                {
                    throw new InvalidOperationException();
                }
            }

            _baseStream.Write(buffer, offset, count);
        }
#endregion

Usage Example

        /// <summary>
        /// Compresses the file at the given path. Returns the path to the
        /// compressed file.
        /// </summary>
        /// <param name="path">The path to compress.</param>
        /// <returns>The path of the compressed file.</returns>
        public string Compress(string path)
        {
            string outputPath = String.Concat(path, ".gz");

            if (File.Exists(outputPath))
            {
                File.Delete(outputPath);
            }

            using (FileStream fs = File.OpenRead(path))
            {
                using (FileStream output = File.Create(outputPath))
                {
                    using (GZipStream gzip = new GZipStream(output, CompressionMode.Compress, CompressionLevel.BestCompression))
                    {
                        byte[] buffer = new byte[4096];
                        int count = 0;

                        while (0 < (count = fs.Read(buffer, 0, buffer.Length)))
                        {
                            gzip.Write(buffer, 0, count);
                        }
                    }
                }
            }

            return outputPath;
        }
All Usage Examples Of Ionic.Zlib.GZipStream::Write