Gzipstream标题和后缀

时间:2016-11-20 22:37:07

标签: c# .net filestream gzipstream

我如何知道使用GzipStream的压缩文件的大小?我知道它有一个标题和后缀。前10个字节 - 它的标题,第二个8字节 - 后缀。我怎么知道后缀中的大小文件?

3 个答案:

答案 0 :(得分:0)

我看到你投票给我之前的答案很可能是因为它是使用Java的一个例子。原理仍然相同,所以你的问题的答案是最后4个字节包含你需要的信息。希望这个答案更能满足您的需求。

以下是解压缩GZip的C#Decompress函数示例,包括获取GZipStream使用的压缩文件的大小:

static public byte[] Decompress(byte[] b)
{
    MemoryStream ms = new MemoryStream(b.length);
    ms.Write(b, 0, b.Length);
    //last 4 bytes of GZipStream = length of decompressed data
    ms.Seek(-4, SeekOrigin.Current);
    byte[] lb = new byte[4];
    ms.Read(lb, 0, 4);
    int len = BitConverter.ToInt32(lb, 0);
    ms.Seek(0, SeekOrigin.Begin);
    byte[] ob = new byte[len];
    GZipStream zs = new GZipStream(ms, CompressionMode.Decompress);
    zs.Read(ob, 0, len);
    returen ob;
}

答案 1 :(得分:0)

我看到你投票给我之前的答案很可能是因为它是使用Java的一个例子。原理仍然相同,所以你的问题的答案是最后4个字节包含你需要的信息。希望这个答案更能满足您的需求。

以下是解压缩GZip的C#Decompress函数示例,包括获取GZipStream使用的压缩文件的大小:

static public byte[] Decompress(byte[] b)
{
    MemoryStream ms = new MemoryStream(b.length);
    ms.Write(b, 0, b.Length);
    //last 4 bytes of GZipStream = length of decompressed data
    ms.Seek(-4, SeekOrigin.Current);
    byte[] lb = new byte[4];
    ms.Read(lb, 0, 4);
    int len = BitConverter.ToInt32(lb, 0);
    ms.Seek(0, SeekOrigin.Begin);
    byte[] ob = new byte[len];
    GZipStream zs = new GZipStream(ms, CompressionMode.Decompress);
    zs.Read(ob, 0, len);
    returen ob;
}

答案 2 :(得分:0)

写得更好一些:

public int GetUncompressedSize(string FileName)
{
   using(BinaryReader br = new BinaryReader(File.OpenRead(pathToFile))
   {
        br.BaseStream.Seek(SeekOrigin.End, -4);
        return br.ReadInt32();
   }
}