July 23, 2013

Extract decompressed file size from a Gzip file

As stated in the documentation, the Property Length of the GZipStream is not supported. so you wont really know the size of the file, your about to extract.

Heres a code that will extract the decompressed filesize:

        /// <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;
            }
        }

GZipStream: http://msdn.microsoft.com...
GZIP file format specification version 4.3 http://tools.ietf.org/html/rfc1952

Total Pageviews