我有一个采用默认参数的python zlib解压缩器,其中数据为字符串:
import zlib
data_decompressed = zlib.decompress(data)
但是,我不知道如何在c#中压缩字符串以在python中解压缩。我已经完成了下一段代码,但是当我尝试解压缩“不正确的标头检查”异常时,出现了错误。
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:
我尝试过使用Shial Bhaiji发布的defalte功能:
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)作为默认值进行解压缩?