Table of Contents

Class MagicNumber

Namespace
HeroKit.FileTypes
Assembly
HeroKit.FileTypes.dll

Detects a file type by fixed bytes at a fixed offset, also called a file signature.

public sealed class MagicNumber : IFileTypeDetector
Inheritance
MagicNumber
Implements
Inherited Members
Extension Methods

Examples

new MagicNumber("89 50 4E 47 0D 0A 1A 0A");          // PNG
new MagicNumber("52 49 46 46 ?? ?? ?? ?? 57 41 56 45"); // RIFF....WAVE, "??" matches any byte
MagicNumber.FromText("ustar", offset: 257);           // tar

Constructors

MagicNumber(string, int)

Creates a detector from hexadecimal bytes separated by spaces. "??" matches any byte.

public MagicNumber(string pattern, int offset = 0)

Parameters

pattern string

The bytes, for example "25 50 44 46 2D".

offset int

The position of the first byte in the file.

Exceptions

ArgumentException

pattern is empty or not hexadecimal.

ArgumentOutOfRangeException

offset is negative.

Properties

Length

Gets the number of bytes the header must have, from the start of the file.

public int Length { get; }

Property Value

int

Methods

FromText(string, int)

Creates a detector from ASCII text, for example "%PDF-".

public static MagicNumber FromText(string text, int offset = 0)

Parameters

text string

The text.

offset int

The position of the first byte in the file.

Returns

MagicNumber

The detector.

Exceptions

ArgumentException

text is empty.

ArgumentOutOfRangeException

offset is negative.

IsMatch(ReadOnlySpan<byte>)

Checks whether the first bytes of a file belong to the file type.

public bool IsMatch(ReadOnlySpan<byte> header)

Parameters

header ReadOnlySpan<byte>

The first bytes of the file; HeaderSize bytes when read from a stream. It can be shorter than the file. For a ZIP file read from a seekable stream, the ZIP central directory follows the first bytes.

Returns

bool

True if the bytes match.