internal static long TryGetFileSize()

in src/Utilities.cs [68:119]


        internal static long TryGetFileSize(string path, double estimatedCompressionRatio)
        {
            try
            {
                var fileInfo = new FileInfo(path);
                long fileSize = 0L;

                if (fileInfo.Extension.EndsWith("zip", StringComparison.OrdinalIgnoreCase))
                {
                    // For Zip archive we can actually calculate the file size
                    using (ZipArchive archive = ZipFile.OpenRead(path))
                    {
                        if (archive.Entries.SafeFastAny())
                        {
                            archive.Entries.ForEach(entry => { fileSize += entry.Length; });
                        }
                    }
                }
                else if (fileInfo.Extension.EndsWith("gz", StringComparison.OrdinalIgnoreCase))
                {
                    // For GZ archives we employ the following logic: if the compressed file is under 400MB,
                    // we will read the uncompressed size from the last 4 bytes of the file.
                    // FOr larger files, we will not rely on the last 4 bytes, as they are modulo 4GB and revert to estimation.
                    if (fileInfo.Length > ReliableGzipSizeEstimationCutoff)
                    {
                        fileSize = (long)(fileInfo.Length * estimatedCompressionRatio);
                    }
                    else
                    {
                        using (var gzStream = File.OpenRead(path))
                        {
                            gzStream.Position = gzStream.Length - 4;
                            var byteArray = new byte[4];
                            gzStream.Read(byteArray, 0, 4);
                            fileSize = BitConverter.ToUInt32(byteArray, 0);
                        }
                    }
                }
                else
                {
                    fileSize = fileInfo.Length;
                }

                return fileSize;
            }
            catch (Exception ex)
            {
                ExtendedConsole.WriteLine(
                    ConsoleColor.DarkYellow, $"Failed to retrieve size for file '{path}'. Error was: {ex.Message}");
            }
            return 0L;
        }