/// <summary> /// Writes a byte array to this stream with compression provided by <see cref="GZipStream"/>. You may write an empty array or a <c>null</c> reference. /// </summary> /// <param name="stream">The stream to write.</param> /// <param name="array">The byte array to write.</param> /// <param name="validityCheck">Indicates whether to write a check code before the byte array. This check code will help detect corrupted data.</param> /// <returns>The number of bytes actually written to the stream.</returns> public static int WriteCompressedByteArray(this Stream stream, byte[] array, bool validityCheck = false) { using (var ms = new MemoryStream()) { using (var gs = new GZipStream(ms, CompressionLevel.Optimal)) { gs.WriteByteArray(array, validityCheck); gs.Flush(); //! must flush } return(stream.WriteByteArray(ms.ToArray())); //! ! You have to write the bytes after closing the gzip stream } }