GZIP Compression Java/C# difference in compression issue

后端 未结 1 1859
死守一世寂寞
死守一世寂寞 2021-01-20 02:59

I\'m adding in compression to my project with the aim of improving speed in the 3G Data communication from Android app to ASP.NET C# Server.

The methods I\'ve resear

1条回答
  •  慢半拍i
    慢半拍i (楼主)
    2021-01-20 03:54

    I get 42 bytes on .NET as well. I suspect you're using an old version of .NET which had a flaw in its compression scheme.

    Here's my test app using your code:

    using System;
    using System.IO;
    using System.IO.Compression;
    using System.Text;
    
    class Program
    {
        static void Main(string[] args)
        {
            var uncompressed = Encoding.UTF8.GetBytes("Mary had a little lamb");
            var compressed = GZIPCompress(uncompressed);
            Console.WriteLine(compressed.Length);
            Console.WriteLine(Convert.ToBase64String(compressed));
        }
    
        static byte[] GZIPCompress(byte[] data)
        {
            using (var memoryStream = new MemoryStream())
            {
                using (var gZipStream = new GZipStream(memoryStream, 
                                                       CompressionMode.Compress))
                {
                    gZipStream.Write(data, 0, data.Length);
                }
    
                return memoryStream.ToArray();
            }
        }
    }
    

    Results:

    42
    H4sIAAAAAAAEAPNNLKpUyEhMUUhUyMksKclJVchJzE0CAHrIujIWAAAA
    

    This is exactly the same as the Java data.

    I'm using .NET 4.5. I suggest you try running the above code on your machine, and compare the results.

    I've just decompressed the base64 data you provided, and it is a valid "compressed" form of "Mary had a little lamb", with 22 bytes in the uncompressed data. That surprises me... and reinforces my theory that it's a framework version difference.

    EDIT: Okay, this is definitely a framework version difference. If I compile with the .NET 3.5 compiler, then use an app.config which forces it to run with that version of the framework, I see 137 bytes as well. Given comments, it looks like this was only fixed in .NET 4.5.

    0 讨论(0)
提交回复
热议问题