Skip to content

Searching streams

StreamExtensions provides general-purpose stream search methods that PndTools uses internally to locate PXML and magic bytes. They are public and available for use in your own code whenever you need to search a seekable stream for a known byte pattern.

Find returns the zero-based byte offset of the first match, or -1 if the pattern is not present.

using PndTools.IO.Extensions;
using var stream = File.OpenRead("data.bin");
var offset = stream.Find([0x89, 0x50, 0x4e, 0x47]); // PNG magic bytes
Console.WriteLine(offset);

Pass a string directly and the method handles the encoding.

var offset = stream.Find("<PXML");

Both overloads accept an optional Direction parameter. Direction.Forward (the default) scans from the current position toward the end. Direction.Backwards starts from the end of the stream and returns the last match — useful when the content you need is appended to the end of a larger file, as with PXML in a PND.

// Forward (default) — first match from the start
var offset = stream.Find("<PXML", Direction.Forward);
// Backwards — last match from the end
var offset = stream.Find("</PXML>", Direction.Backwards);

GetBytes extracts a slice of the stream by start and end position.

var data = stream.GetBytes(start: offset, end: offset + 512);

Both positions are zero-based. start is inclusive, end is exclusive. Throws ArgumentOutOfRangeException if end exceeds the stream length or start is negative.

FindAsync and GetBytesAsync are async counterparts that accept an optional CancellationToken. See the async and await guide for usage examples.