Read inside a larger stream
Advanced · C#. The two-byte prefix belongs to surrounding data. Selected addresses are stream coordinates, so length starts at 2 + 2.
Run this example
Prerequisites: the repository's .NET 10 SDK and a checkout of this source. Run from the repository root:
dotnet run --project docs/examples/CStructSharp.Docs.Examples.csproj -c Release -- positioned-stream
The runner checks length address 4; inspection preserves Position 2; length reads 6. Success includes PASS positioned-stream.
This example uses the C# API. Browser capabilities and result shapes are described in the browser guide.
Complete program
The layout, options, input bytes, helper methods, and required types are all included. To adapt it outside the repository, create a .NET 10 console project, add CStructSharp, and replace Program.cs with this complete file. These examples follow the source version; use a matching package when testing a release.
Download the complete C# source.
// Generated from executable documentation examples. Edit the source region, then regenerate.
using System;
using System.IO;
using System.IO.Pipelines;
using System.Linq;
using System.Buffers;
using System.Collections.Generic;
using System.Dynamic;
using System.Globalization;
using System.Numerics;
using System.Runtime.CompilerServices;
using System.Threading;
using System.Threading.Tasks;
using CStructSharp;
using CStructSharp.Codecs;
using CStructSharp.Diagnostics;
using CStructSharp.Introspection;
using CStructSharp.Values;
internal static partial class Program
{
public static void Main()
{
PositionedStream();
Console.WriteLine("PASS positioned-stream");
}
private static void PositionedStream()
{
var layout = new CStruct("struct header { uint16 kind; uint32 length; };");
using var stream = new MemoryStream([0xEE, 0xEE, 2, 0, 6, 0, 0, 0]);
stream.Position = 2;
Equal(4L, layout.ResolveAddress(stream, "header.length"));
Equal(2L, stream.Position);
StructValue header = layout.Parse(stream, "header");
Equal(6U, header.Get<uint>("length"));
}
private static void Equal<T>(T expected, T actual)
{
if (!EqualityComparer<T>.Default.Equals(expected, actual))
{
throw new InvalidOperationException($"Expected '{expected}', received '{actual}'.");
}
}
}
Try it and diagnose mistakes
Start the stream at Position 0.
Answer: The prefix becomes part of the header input and values change. Restore Position 2. The program contains assertions for its original inputs. When changing an input intentionally, update the expected assertion too; an unchanged assertion is not evidence that the new value is wrong.
Continue with the related guide or choose another recipe.