PROWAREtech

articles » current » dot-net » identify-gzip-files

.NET: Identify GZip Compressed Files

How to determine if a file is a GZip compressed file (compressed with GZipStream); written in C#.

See also: Identify Brotli-compressed Files.

Determine if a file is compressed with the GZipStream class by reading the file's header bytes and checking for the specific GZip signature. GZip files have a unique "magic number" at the beginning: the first two bytes are 0x1F and 0x8B, which identify the file as being in GZip format.

This approach is lightweight and allows for quickly verifying if a file is compressed with GZipStream without fully decompressing it.

NOTE: One can always try to decompress a GZip compressed file, and if it fails, then it is not a GZip file.

Example Code


using System;
using System.IO;

public class Program
{
	public static bool IsGZipFile(string filePath)
	{
		// Open the file to check the header
		using (var fileStream = new FileStream(filePath, FileMode.Open, FileAccess.Read))
		{
			if (fileStream.Length < 2)
			{
				return false; // File is too short to be a valid GZip file
			}

			int byte1 = fileStream.ReadByte();
			int byte2 = fileStream.ReadByte();

			// Check for the GZip signature (0x1F, 0x8B)
			return byte1 == 0x1F && byte2 == 0x8B;
		}
	}

	public static void Main()
	{
		string path = "file.gz";
		bool isGZip = IsGZipFile(path);

		Console.WriteLine(isGZip ? "The file is a GZip file." : "The file is not a GZip file.");
	}
}

PROWAREtech

Hello there! How can I help you today?
Ask any question

PROWAREtech

This site uses cookies. Cookies are simple text files stored on the user's computer. They are used for adding features and security to this site. Read the privacy policy.
ACCEPT REJECT