如何在 C# 中压缩数据以在 zlib 中解压缩 python

How to compress data in C# to be decompressed in zlib python

我有一个 python zlib 解压缩器,它采用如下默认参数,其中数据是字符串:

  import zlib
  data_decompressed = zlib.decompress(data)

但是,我不知道如何在 c# 中压缩要在 python 中解压缩的字符串。我已经托盘了下一段代码,但是当我尝试解压缩时 'incorrect header check' 异常被抛出。

    static byte[] ZipContent(string entryName)
    {
        // remove whitespace from xml and convert to byte array
        byte[] normalBytes;
        using (StringWriter writer = new StringWriter())
        {
            //xml.Save(writer, SaveOptions.DisableFormatting);
            System.Text.ASCIIEncoding encoding = new System.Text.ASCIIEncoding();
            normalBytes = encoding.GetBytes(writer.ToString());
        }

        // zip into new, zipped, byte array
        using (Stream memOutput = new MemoryStream())
        using (ZipOutputStream zipOutput = new ZipOutputStream(memOutput))
        {
            zipOutput.SetLevel(6);

            ZipEntry entry = new ZipEntry(entryName);
            entry.CompressionMethod = CompressionMethod.Deflated;
            entry.DateTime = DateTime.Now;
            zipOutput.PutNextEntry(entry);

            zipOutput.Write(normalBytes, 0, normalBytes.Length);
            zipOutput.Finish();

            byte[] newBytes = new byte[memOutput.Length];
            memOutput.Seek(0, SeekOrigin.Begin);
            memOutput.Read(newBytes, 0, newBytes.Length);

            zipOutput.Close();

            return newBytes;
        }
    }

有人可以帮助我吗? 谢谢。

更新 1:

我试过使用 defalte 函数,正如 Shiraz Bhaiji 发布的那样:

    public static byte[] Deflate(byte[] data)
    {
        if (null == data || data.Length < 1) return null;
        byte[] compressedBytes;

        //write into a new memory stream wrapped by a deflate stream
        using (MemoryStream ms = new MemoryStream())
        {
            using (DeflateStream deflateStream = new DeflateStream(ms, CompressionMode.Compress, true))
            {
                //write byte buffer into memorystream
                deflateStream.Write(data, 0, data.Length);
                deflateStream.Close();

                //rewind memory stream and write to base 64 string
                compressedBytes = new byte[ms.Length];
                ms.Seek(0, SeekOrigin.Begin);
                ms.Read(compressedBytes, 0, (int)ms.Length);

            }
        }
        return compressedBytes;
    }

问题是为了在 python 代码中正常工作,我必须添加“-zlib.MAX_WBITS”参数来解压缩,如下所示:

    data_decompressed = zlib.decompress(data, -zlib.MAX_WBITS)

所以,我的新问题是:是否可以在 C# 中编写一个 deflate 方法,其压缩结果可以默认使用 zlib.decompress(data) 解压缩?

在 C# 中,DeflateStream class 支持 zlib。参见:

https://docs.microsoft.com/en-us/dotnet/api/system.io.compression.deflatestream?view=netframework-4.8