解压缩后的 GZipStream 长度





5.00/5 (2投票s)
从 Gzip 文件中提取解压缩文件的大小!
引言
如文档所述,GZipStream
的 Length
属性不受支持。因此,你无法真正知道你即将提取的文件的大小。
使用代码
/// <summary>
/// Extracts the original filesize of the compressed file.
/// </summary>
/// <param name="fi">GZip file to handle</param>
/// <returns>Size of the compressed file, when its decompressed.</returns>
/// <remarks>More information at http://tools.ietf.org/html/rfc1952 section 2.3</remarks>
public static int GetGzOriginalFileSize(string fi)
{
return GetGzOriginalFileSize(new FileInfo(fi));
}
/// <summary>
/// Extracts the original filesize of the compressed file.
/// </summary>
/// <param name="fi">GZip file to handle</param>
/// <returns>Size of the compressed file, when its decompressed.</returns>
/// <remarks>More information at http://tools.ietf.org/html/rfc1952 section 2.3</remarks>
public static int GetGzOriginalFileSize(FileInfo fi)
{
try
{
using (FileStream fs = fi.OpenRead())
{
try
{
byte[] fh = new byte[3];
fs.Read(fh, 0, 3);
if (fh[0] == 31 && fh[1] == 139 && fh[2] == 8) //If magic numbers are 31 and 139 and the deflation id is 8 then...
{
byte[] ba = new byte[4];
fs.Seek(-4, SeekOrigin.End);
fs.Read(ba, 0, 4);
return BitConverter.ToInt32(ba, 0);
}
else
return -1;
}
finally
{
fs.Close();
}
}
}
catch (Exception)
{
return -1;
}
}
很简单,你只需调用 GetGzOriginalFileSize 方法并解析文件路径或 FileInfo 对象,即可获得解压缩后的文件大小。
资源
历史
2013-08-16:首次发布。