---
title: "Audit HTML edit byte ranges in C#"
url: https://recursiveai.org/onehtml/cookbook/audit-html-edit-byte-ranges/
description: "Audit HTML edits in C# with old and new byte ranges, replacement bytes, and fallback levels. Reconstruct UTF-8 output from a downloadable example."
version: "1.6.0"
---

# Audit HTML edit byte ranges in C#

**onehtml** is a free, open-source HTML library for .NET from Recursive AI. MIT or Apache-2.0, no native dependencies.

[NuGet](https://www.nuget.org/packages/RecursiveAI.OneHtml) · [GitHub](https://github.com/recursive-ai-oss/onehtml-csharp) · [Docs](https://recursiveai.org/onehtml/docs/) · [Download example (.zip)](https://recursiveai.org/onehtml/cookbook/audit-html-edit-byte-ranges/audit-html-edit-byte-ranges.zip)

Record the exact bytes an HTML edit replaces, including changes to multibyte UTF-8 text.

```shell
dotnet add package RecursiveAI.OneHtml
```

Requires [.NET 10](https://dotnet.microsoft.com/download/dotnet/10.0) (net10.0); .NET 9 and earlier aren’t supported.

```csharp
using RecursiveAI.OneHtml;
using RecursiveAI.OneHtml.Editing;

using System.Text;

var bytes = Encoding.UTF8.GetBytes("<meta charset=utf-8><p>café</p>");
var doc = Document.Parse(bytes);
var result = doc.Apply([
    Edit.ReplaceText(doc.Root.QuerySelector("p"), "茶")
]);
if (!result.Succeeded) throw new Exception(result.Failure);
foreach (var range in result.Changes!.Ranges)
    Console.WriteLine($"{range.OldByteRange.Start}..{range.OldByteRange.End}: {range.NewText}");
```

Unzip [the example](https://recursiveai.org/onehtml/cookbook/audit-html-edit-byte-ranges/audit-html-edit-byte-ranges.zip), then `dotnet run`.

```text
23..28: 茶
```

## The full program

The input is inline UTF-8 HTML: `<meta charset=utf-8><p>café</p>`. This program reconstructs the output from the original bytes and the reported patches.

```csharp
using RecursiveAI.OneHtml;
using RecursiveAI.OneHtml.Editing;

using System.Text;

var bytes = Encoding.UTF8.GetBytes("<meta charset=utf-8><p>café</p>");
var doc = Document.Parse(bytes);
var result = doc.Apply([
    Edit.ReplaceText(doc.Root.QuerySelector("p"), "茶")
]);
if (!result.Succeeded) throw new Exception(result.Failure);
foreach (var range in result.Changes!.Ranges)
    Console.WriteLine($"{range.OldByteRange.Start}..{range.OldByteRange.End}: {range.NewText}");
using var patched = new MemoryStream();
int cursor = 0;
foreach (var range in result.Changes!.Ranges)
{
    patched.Write(bytes.AsSpan(cursor, range.OldByteRange.Start - cursor));
    patched.Write(range.NewBytes.Span);
    cursor = range.OldByteRange.End;
    Console.WriteLine($"Text: {range.OldTextRange} -> {range.NewTextRange}");
    Console.WriteLine($"Bytes: {range.OldByteRange} -> {range.NewByteRange}");
    Console.WriteLine($"Fallback level: {range.FallbackLevel}");
}
patched.Write(bytes.AsSpan(cursor));
var output = patched.ToArray();
Console.WriteLine(Encoding.UTF8.GetString(output));
Console.WriteLine($"Matches edited bytes: {output.AsSpan().SequenceEqual(result.Document!.ToLosslessBytes())}");
```

`dotnet run` prints:

```text
23..28: 茶
Text: SourceRange { Start = 23, End = 27, IsPresent = True, Length = 4 } -> SourceRange { Start = 23, End = 24, IsPresent = True, Length = 1 }
Bytes: SourceRange { Start = 23, End = 28, IsPresent = True, Length = 5 } -> SourceRange { Start = 23, End = 26, IsPresent = True, Length = 3 }
Fallback level: 0
<meta charset=utf-8><p>茶</p>
Matches edited bytes: True
```

If an edit fails, `Succeeded` is false and there is no new document; check it before reading the change set.

## Variations

### Report a widened rewrite

This input omits the body start tag. Adding its class requires an enclosing rewrite rather than a local attribute splice.

```csharp
using RecursiveAI.OneHtml;
using RecursiveAI.OneHtml.Editing;

using System.Text;

var doc = Document.Parse(Encoding.UTF8.GetBytes("<html><p>x</html>"));
var result = doc.Apply([
    Edit.SetAttribute(doc.Root.QuerySelector("body"), "class", "c")
]);
Console.WriteLine($"Applied: {result.Succeeded}");
if (result.Succeeded)
    foreach (var range in result.Changes!.Ranges)
        Console.WriteLine($"Fallback level: {range.FallbackLevel}");
else
    Console.WriteLine(result.Failure);
```

```text
Applied: True
Fallback level: 1
```

## Related recipes

- [Apply HTML edits atomically in C#](https://recursiveai.org/onehtml/cookbook/apply-html-edits-atomically/)
- [Update an accessibility tree after an HTML edit in C#](https://recursiveai.org/onehtml/cookbook/update-accessibility-tree-after-dom-edit/)
- [Edit HTML without rewriting untouched source](https://recursiveai.org/onehtml/cookbook/edit-html-csharp-lossless/)

## The short answer

Parse the original bytes, apply the edits, and read `result.Changes.Ranges` after success. Each range names the old and new byte positions and carries `NewBytes`, the exact replacement payload. Copy the untouched input segments around those replacements to reconstruct the output.

The example replaces “café” with “茶” in declared UTF-8 HTML. The old text occupies four UTF-16 units but five bytes; its replacement occupies one UTF-16 unit but three bytes. The full program prints both coordinate systems and confirms that applying the byte patches produces the edited document’s bytes.

## How do you audit HTML edit byte ranges in C#?

The [editing documentation](https://recursiveai.org/onehtml/docs/editing/) calls the range list the “audit diff.” It is sorted and nonoverlapping. Each item carries `OldByteRange`, `NewByteRange`, `NewBytes`, the corresponding text ranges, the new text, the indexes of the contributing edits, and a fallback level.

The old ranges refer to the original input, not a buffer already modified by earlier patches. The reconstruction loop therefore advances an input cursor: copy unchanged bytes before the next old range, write its replacement bytes, then skip to the old range’s end. After the last replacement, copy the remaining input. This also handles insertion ranges, whose old length is zero, and deletion ranges, whose replacement payload is empty.

Keep the original bytes alongside the range list if you need to inspect the removed content later. The new text is convenient to display, but `NewBytes` is what belongs in a byte-for-byte reconstruction. Decoding and re-encoding the entire input would defeat the purpose of preserving the unchanged parts.

## What does byte offset mean?

A C# string uses UTF-16 positions, while this input is UTF-8 bytes. Treating a text offset as a byte offset can split an encoded character or target the wrong stretch of source. The example declares its encoding in `<meta charset=utf-8>` and passes `Encoding.UTF8.GetBytes(...)` into the parser. Both choices are deliberate: the bytes must be decoded as the encoding in which they were produced.

The [range API](https://recursiveai.org/onehtml/docs/editing/) provides both coordinate systems rather than requiring callers to guess. Its source ranges use a start position and an exclusive end position; the difference is the length. Notice that the replacement changes the output’s length. Later new positions can shift even though later old positions still identify locations in the original input.

Do not use a string-only parse for this byte audit. With no original bytes, the API’s byte ranges use text positions and `NewBytes` is empty. A string parse is useful for DOM editing, but it does not carry the byte-level input this reconstruction needs.

### Can an edit rewrite more bytes than I targeted?

Yes. A local splice must parse back into the intended tree. If it does not, the editor can widen the rewrite to an enclosing element. `FallbackLevel` is zero for a local change and positive for an enclosing rewrite. The variation edits a synthesized body start tag that has no source bytes of its own, and reports a positive level.

Inside a fallback range, the subtree is canonically serialized; bytes there are not preserved. Outside it, they are. Log the level and full range rather than describing every edit as a single-attribute patch. `result.Fallbacks` also supplies the edit index, range, level and reason. If no surrounding rewrite can express the intended HTML, the transaction fails and supplies no edited document. See the [fallback rules](https://recursiveai.org/onehtml/docs/editing/#fallback) when deciding whether your application should accept a widened rewrite.
