To check if a file is an image, PDF, or audio file by inspecting its content, you should analyze the
file signature (also known as the "magic number")—a specific byte pattern at the beginning of the file that indicates its type.
1. Read the File Header (Magic Number)
Here's a C# example:
public static string GetFileType(string filePath)
{
byte[] header = new byte[8];
using (FileStream fs = new FileStream(filePath, FileMode.Open, FileAccess.Read))
{
fs.Read(header, 0, header.Length);
}
// Check against known signatures
if (header.Take(3).SequenceEqual(new byte[] { 0xFF, 0xD8, 0xFF }))
return "JPEG image";
if (header.Take(8).SequenceEqual(new byte[] { 0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A }))
return "PNG image";
if (header.Take(4).SequenceEqual(new byte[] { 0x25, 0x50, 0x44, 0x46 }))
return "PDF document";
if (header.Take(4).SequenceEqual(new byte[] { 0x49, 0x44, 0x33 })) // or use offset for ID3v2
return "MP3 audio";
if (header.Take(4).SequenceEqual(new byte[] { 0x52, 0x49, 0x46, 0x46 }))
return "WAV or AVI (need more info)";
return "Unknown";
}
2. Common Signatures
File Type
Magic Number (Hex)
Description
JPEG
FF D8 FF
First 3 bytes
PNG
89 50 4E 47 0D 0A 1A 0A
First 8 bytes
PDF
25 50 44 46
%PDF
MP3
49 44 33
ID3 at start (ID3v2)
WAV
52 49 46 46
RIFF (check next bytes)
GIF
47 49 46 38
GIF8
To distinguish between WAV and AVI, you'd need to check the next few bytes after
RIFF.
3. Notes
This method is more secure and reliable than using file extensions.
To support more formats, extend the signature table.
This approach works well for validation before saving or processing files.
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.
To check if a file is an image, PDF, or audio file by inspecting its content, you should analyze the file signature (also known as the "magic number")—a specific byte pattern at the beginning of the file that indicates its type.
1. Read the File Header (Magic Number)
Here's a C# example:
2. Common Signatures
FF D8 FF89 50 4E 47 0D 0A 1A 0A25 50 44 46%PDF49 44 33ID3at start (ID3v2)52 49 46 46RIFF(check next bytes)47 49 46 38GIF8To distinguish between
WAVandAVI, you'd need to check the next few bytes afterRIFF.3. Notes