PROWAREtech

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

.NET: Identify Brotli Compressed Files

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

See also: Identify GZip Files.

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

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

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

Example Code


using System;
using System.IO;

public class Program
{
	public static bool IsBrotliFile(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 Brotli file
			}

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

			// Check for the Brotli signature (0xCE, 0xB2)
			return byte1 == 0xCE && byte2 == 0xB2;
		}
	}

	public static void Main()
	{
		string path = "file.br";
		bool isBrotli = IsBrotliFile(path);

		Console.WriteLine(isBrotli ? "The file is a Brotli-compressed file." : "The file is not a Brotli-compressed 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