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
patternstringThe bytes, for example "25 50 44 46 2D".
offsetintThe position of the first byte in the file.
Exceptions
- ArgumentException
patternis empty or not hexadecimal.- ArgumentOutOfRangeException
offsetis negative.
Properties
Length
Gets the number of bytes the header must have, from the start of the file.
public int Length { get; }
Property Value
Methods
FromText(string, int)
Creates a detector from ASCII text, for example "%PDF-".
public static MagicNumber FromText(string text, int offset = 0)
Parameters
Returns
- MagicNumber
The detector.
Exceptions
- ArgumentException
textis empty.- ArgumentOutOfRangeException
offsetis negative.
IsMatch(ReadOnlySpan<byte>)
Checks whether the first bytes of a file belong to the file type.
public bool IsMatch(ReadOnlySpan<byte> header)
Parameters
headerReadOnlySpan<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.