Validating a file's format using its signature (magic number) is much more reliable than checking the file extension, because it inspects the actual
byte content of the file header.
What is a File Signature / Magic Number?
A magic number is a unique sequence of bytes at the beginning of a file that identifies its type.
File Type
Signature (Hex)
ASCII Example
PDF
25 50 44 46
%PDF
PNG
89 50 4E 47 0D 0A 1A 0A
.PNG....
JPG
FF D8 FF
ZIP
50 4B 03 04
PK..
DOCX
50 4B 03 04
ZIP container
How to Read and Validate Signature in C#
using System;
using System.IO;
public class FileSignatureValidator
{
public static bool IsPdf(string filePath)
{
byte[] pdfSignature = { 0x25, 0x50, 0x44, 0x46 }; // %PDF
return HasSignature(filePath, pdfSignature);
}
public static bool IsPng(string filePath)
{
byte[] pngSignature = { 0x89, 0x50, 0x4E, 0x47 };
return HasSignature(filePath, pngSignature);
}
public static bool HasSignature(string filePath, byte[] expectedSignature)
{
if (!File.Exists(filePath))
return false;
using (var stream = File.OpenRead(filePath))
{
byte[] buffer = new byte[expectedSignature.Length];
int read = stream.Read(buffer, 0, buffer.Length);
if (read != expectedSignature.Length)
return false;
for (int i = 0; i < expectedSignature.Length; i++)
{
if (buffer[i] != expectedSignature[i])
return false;
}
return true;
}
}
}
Usage:
if (FileSignatureValidator.IsPdf("document.pdf"))
Console.WriteLine("This is a PDF file.");
else
Console.WriteLine("Invalid PDF.");
Tips:
For formats like .docx or .xlsx, check the ZIP signature
and inspect internal files (like [Content_Types].xml) for deeper validation.
For larger sets of formats, you can build a dictionary of known signatures.
Markdown for AI
A clean, structured version of this page for AI assistants and LLMs.
We use cookies to ensure you have the best browsing experience on our website. By using our site, you
acknowledge that you have read and understood our
Cookie Policy &
Privacy Policy.
Validating a file's format using its signature (magic number) is much more reliable than checking the file extension, because it inspects the actual byte content of the file header.
What is a File Signature / Magic Number?
A magic number is a unique sequence of bytes at the beginning of a file that identifies its type.
%PDF.PNG....PK..How to Read and Validate Signature in C#
Usage:
Tips:
.docxor.xlsx, check the ZIP signature and inspect internal files (like[Content_Types].xml) for deeper validation.