GZIP文件C#的总长度

时间:2011-01-12 06:57:16

标签: c# gzip gunzip

我有一个大小为几GB的压缩文件,我想获得解压缩内容的大小但不想在C#中实际解压缩文件,我可以使用哪些库?当我右键单击.gz文件并转到属性时,在Archive选项卡下有一个属性名称TotalLength,它显示此值。但我希望以编程方式使用C#来获取它。任何想法?

4 个答案:

答案 0 :(得分:11)

gz文件的最后4个字节包含长度。

所以它应该是这样的:

using(var fs = File.OpenRead(path))
{
  fs.Position = fs.Length - 4;
  var b = new byte[4];
  fs.Read(b, 0, 4);
  uint length = BitConverter.ToUInt32(b, 0);
  Console.WriteLine(length);
}

答案 1 :(得分:4)

.gz文件的最后一个字节是未压缩的输入大小,模数为2 ^ 32。如果未压缩的文件不大于4GB,则只读取文件的最后4个字节。如果你有一个更大的文件,我不确定是否可以在不解压缩流的情况下获得。

答案 2 :(得分:2)

编辑:看看Leppie和Gabe的答案;我保留这个(而不是删除它)的唯一原因是,如果你怀疑长度是> 0,则可能是必要的。 4GB


对于gzip,这些数据似乎没有直接可用 - 我查看了GZipStreamSharpZipLib等价物 - 都不起作用。我能建议的最好是在本地运行它:

    long length = 0;
    using(var fs = File.OpenRead(path))
    using (var gzip = new GZipStream(fs, CompressionMode.Decompress)) {
        var buffer = new byte[10240];
        int count;
        while ((count = gzip.Read(buffer, 0, buffer.Length)) > 0) {
            length += count;
        }
    }

如果是拉链,那么SharpZipLib:

    long size = 0;
    using(var zip = new ZipFile(path)) {
        foreach (ZipEntry entry in zip) {
            size += entry.Size;
        }
    }

答案 3 :(得分:-1)

public static long mGetFileLength(string strFilePath)
{
    if (!string.IsNullOrEmpty(strFilePath))
    {
        System.IO.FileInfo info = new System.IO.FileInfo(strFilePath);
        return info.Length;
    }

    return 0; 
}