Decompress byte array to string via BinaryReader yields empty string

前端 未结 1 652
[愿得一人]
[愿得一人] 2020-12-31 21:10

I am trying to decompress a byte array and get it into a string using a binary reader. When the following code executes, the inStream position changes from 0 to the length

相关标签:
1条回答
  • 2020-12-31 21:55

    You haven't shown how is the data being compressed, but here's a full example of compressing and decompressing a buffer:

    using System;
    using System.IO;
    using System.IO.Compression;
    using System.Text;
    
    class Program
    {
        static void Main()
        {
            var test = "foo bar baz";
    
            var compressed = Compress(Encoding.UTF8.GetBytes(test));
            var decompressed = Decompress(compressed);
            Console.WriteLine(Encoding.UTF8.GetString(decompressed));
        }
    
        static byte[] Compress(byte[] data)
        {
            using (var compressedStream = new MemoryStream())
            using (var zipStream = new GZipStream(compressedStream, CompressionMode.Compress))
            {
                zipStream.Write(data, 0, data.Length);
                zipStream.Close();
                return compressedStream.ToArray();
            }
        }
    
        static 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();
            }
        }
    }
    
    0 讨论(0)
提交回复
热议问题