有没有办法知道GzipStream
.net类是否已压缩(或不压缩)byte []?
修改 只想知道byte []数组是否已被压缩(因为我将始终使用GzipStream进行压缩和解压缩)
答案 0 :(得分:8)
GZipStream是DeflateStream,其中包含额外的标题和预告片。
格式在RFC 1952中指定。
.NET 4.0 GZipStream类将以下字节写为标题:
byte[] headerBytes = new byte[] { 0x1f, 0x8b, 8, 0, 0, 0, 0, 0, 4, 0 };
if (compressionLevel == 10)
{
headerBytes[8] = 2;
}
预告片包含CRC32校验和以及未压缩数据的长度。
答案 1 :(得分:3)
感谢@ dtd的解释,这对我有用:(@ stackoverflowuser,你可能想要这个吗?)
public static class CompressionHelper
{
public static byte[] GZipHeaderBytes = {0x1f, 0x8b, 8, 0, 0, 0, 0, 0, 4, 0};
public static byte[] GZipLevel10HeaderBytes = {0x1f, 0x8b, 8, 0, 0, 0, 0, 0, 2, 0};
public static bool IsPossiblyGZippedBytes(this byte[] a)
{
var yes = a.Length > 10;
if (!yes)
{
return false;
}
var header = a.SubArray(0, 10);
return header.SequenceEqual(GZipHeaderBytes) || header.SequenceEqual(GZipLevel10HeaderBytes);
}
}
答案 2 :(得分:1)
你可以查看魔术头的前几个字节,看它是否被gzip压缩,但除非.net压缩器将其他信息写入其中一个注释或其他可选字段,否则你可能无法告诉 压缩机是谁。
http://www.onicos.com/staff/iz/formats/gzip.html
您还可以查看操作系统类型字段以查看它是FAT还是NTFS,但仍然没有告诉您它是由C#编写的......