How to use the 7z SDK to compress and decompress a file

后端 未结 3 1310
花落未央
花落未央 2020-11-29 06:57

According to this link How do I create 7-Zip archives with .NET? , WOPR tell us how to compress a file with LMZA (7z compression algorithm) using 7z SDK ( http://www.7-zip.o

3条回答
  •  情深已故
    2020-11-29 07:13

    I needed LZMA compression for sending images over network, not sure it's the best alternative but at least it works in my ecosystem! So here is something that should work right away for that purpose.

    using System;
    using System.IO;
    using SevenZip;
    
      public class LZMA{
        public static byte[] Compress(byte[] toCompress)
          {
            SevenZip.Compression.LZMA.Encoder coder = new SevenZip.Compression.LZMA.Encoder();
    
            using(MemoryStream input = new MemoryStream(toCompress))
            using(MemoryStream output = new MemoryStream()){
    
              coder.WriteCoderProperties(output);
    
              for (int i = 0; i < 8; i++) {
                output.WriteByte((byte)(input.Length >> (8 * i)));
              }
    
              coder.Code(input, output, -1, -1, null);
              return output.ToArray();
            }
          }
    
        public static byte[] Decompress(byte[] toDecompress)
        {
            SevenZip.Compression.LZMA.Decoder coder = new SevenZip.Compression.LZMA.Decoder();
    
            using(MemoryStream input = new MemoryStream(toDecompress))
            using(MemoryStream output = new MemoryStream()){
    
              // Read the decoder properties
              byte[] properties = new byte[5];
              input.Read(properties, 0, 5);
    
    
              // Read in the decompress file size.
              byte [] fileLengthBytes = new byte[8];
              input.Read(fileLengthBytes, 0, 8);
              long fileLength = BitConverter.ToInt64(fileLengthBytes, 0);
    
              coder.SetDecoderProperties(properties);
              coder.Code(input, output, input.Length, fileLength, null);
    
              return output.ToArray();
            }
        }
      }
    

提交回复
热议问题