-1

i have a method which Decompress byte array and i need opposite of this function(mean Compress).i googeled a lot but didnot find exactly opposit of this function

public static byte[] Decompress(byte[] B)
{

        MemoryStream ms = new MemoryStream(B);
        GZipStream gzipStream = new GZipStream((Stream)ms, CompressionMode.Decompress);
        byte[] buffer = new byte[4];
        ms.Position = checked(ms.Length - 5L);
        ms.Read(buffer, 0, 4);
        int count = BitConverter.ToInt32(buffer, 0);
        ms.Position = 0L;
        byte[] AR = new byte[checked(count - 1 + 1)];
        gzipStream.Read(AR, 0, count);
        gzipStream.Dispose();
        ms.Dispose();
        return AR;

}
ehsan
  • 29
  • 1
  • 6
  • Not sure what you were googling for, you just need to understand what this function does and then reverse the steps. The function first reads the last 4 bytes from the stream and interprets them as a 32bit signed integer representing `count` -- the size of the uncompressed data. It allocates an array of `count` bytes, and then decompresses `count` bytes from the beginning of the stream. | So, the reverse would be -- compress the data to the stream, then write (raw, directly to the memory stream) the size of uncompressed data as 4 bytes. – Dan Mašek Oct 20 '19 at 11:11

1 Answers1

2

You're over complicating the decompress part. You can achieve most what you want with purely streams and copying.

        private byte[] Compress(byte[] data)
        {
            using (var compressedStream = new MemoryStream())
            using (var zipStream = new GZipStream(compressedStream, CompressionMode.Compress))
            {
                zipStream.Write(data, 0, data.Length);
                return compressedStream.ToArray();
            }
        }

        private byte[] Decompress(byte[] data)
        {
            using (var compressedStream = new MemoryStream(data))
            using (var zipStream = new GZipStream(compressedStream, CompressionMode.Decompress))
            using (var resultStream = new MemoryStream())
            {
                zipStream.CopyTo(resultStream);
                return resultStream.ToArray();
            }
        }
d.moncada
  • 16,900
  • 5
  • 53
  • 82
  • tnx.but your compress method didnot work for me. i need a method(Compress method) to compress my decompressd file which decompressed by that method.so i only need a method that mach to my decompressed file – ehsan Oct 19 '19 at 21:23
  • @ehsan why not use the decompress method i provided instead? – d.moncada Oct 19 '19 at 22:04
  • i cant bro.bcz im using this code on a decompiled program – ehsan Oct 20 '19 at 05:06