C# 中的 Python 函数
zlib.decompress()
相当于什么?我需要使用 C# 解压一些 zlib 文件,但我不知道该怎么做。
Python 示例:
import zlib
file = open("myfile", mode = "rb")
data = zlib.decompress(file.read())
uncompressed_output = open("output_file", mode = "wb")
uncompressed_output.write(data)
我尝试使用
System.IO.Compression.DeflateStream
类,但对于我尝试的每个文件,它都会给我一个例外,即该文件在解码时包含无效数据。
byte[] binary = new byte[1000000];
using (DeflateStream compressed_file = new DeflateStream(new FileStream(@"myfile", FileMode.Open, FileAccess.Read), CompressionMode.Decompress))
compressed_file.Read(binary, 0, 1000000); //exception here
using (BinaryWriter outputFile = new BinaryWriter(new FileStream(@"output_file", FileMode.Create, FileAccess.Write)))
outputFile.Write(binary);
//Reading the file like normal with a BinaryReader and then turning it into a MemoryStream also didn't work
我应该提到这些文件是 ZLIB 压缩文件。他们从 78 9C 标头开始。
所以,幸运的是,我找到了这篇文章:https://stackoverflow.com/a/33855097/10505778
基本上,文件必须去除 2 个标头字节 (78 9C)。虽然 9C 在解压缩中很重要(它指定是否使用了预设字典),但我不需要它,但我很确定修改它以适应它并不困难:
byte[] binary, decompressed;
using (BinaryReader file = new BinaryReader(new FileStream(@"myfile", FileMode.Open, FileAccess.Read, FileShare.Read))
binary = file.ReadBytes(int.MaxValue); //read the entire file
output = new byte[int.MaxValue];
int outputSize;
using (MemoryStream memory_stream = new MemoryStream(binary, false))
{
memory_stream.Read(decompressed, 0, 2); //discard 2 bytes
using (DeflateStream compressed_file = new DeflateStream(memory_stream, CompressionMode.Decompress)
outputSize = compressed_file.Read(decompressed, 0, int.MaxValue);
}
binary = new byte[outputSize];
Array.Copy(decompressed, 0, binary, 0, outputSize);
using (BinaryWriter outputFile = new BinaryWriter(new FileStream(@"output_file", FileMode.Create, FileAccess.Write)))
outputFile.Write(binary);
在.NET 8中,有一个ZLibStream库允许我们解压缩lib文件。
这是一个代码片段,展示了如何使用该库
using System.IO.Compression;
...
static string Decompress(string CompressedFileName)
{
// function takes a filename and returns the decompressed contents
using (FileStream compressedFileStream = File.Open(CompressedFileName, FileMode.Open))
{
using (var ds = new ZLibStream(compressedFileStream, CompressionMode.Decompress))
{
using (var sr = new StreamReader(ds))
{
return sr.ReadToEnd();
}
}
}
}