/// <summary> /// Compresses byte array with LZMA algorithm (C# inside) /// </summary> /// <param name="data">Byte array to compress</param> /// <returns>Compressed byte array</returns> public static byte[] CompressBytes(byte[] data) { using (var inStream = new MemoryStream(data)) { using (var outStream = new MemoryStream()) { var encoder = new Encoder(); WriteLzmaProperties(encoder); encoder.WriteCoderProperties(outStream); long streamSize = inStream.Length; for (int i = 0; i < 8; i++) outStream.WriteByte((byte) (streamSize >> (8*i))); encoder.Code(inStream, outStream, -1, -1, null); return outStream.ToArray(); } } }
/// <summary> /// Compresses the specified stream with LZMA algorithm (C# inside) /// </summary> /// <param name="inStream">The source uncompressed stream</param> /// <param name="outStream">The destination compressed stream</param> /// <param name="inLength">The length of uncompressed data (null for inStream.Length)</param> /// <param name="codeProgressEvent">The event for handling the code progress</param> public static void CompressStream(Stream inStream, Stream outStream, int? inLength, EventHandler<ProgressEventArgs> codeProgressEvent) { if (!inStream.CanRead || !outStream.CanWrite) { throw new ArgumentException("The specified streams are invalid."); } var encoder = new Encoder(); WriteLzmaProperties(encoder); encoder.WriteCoderProperties(outStream); long streamSize = inLength.HasValue ? inLength.Value : inStream.Length; for (int i = 0; i < 8; i++) { outStream.WriteByte((byte) (streamSize >> (8*i))); } encoder.Code(inStream, outStream, -1, -1, new LzmaProgressCallback(streamSize, codeProgressEvent)); }