---
title: "Edit HTML without changing its encoding in C#"
url: https://recursiveai.org/onehtml/cookbook/edit-html-without-changing-file-encoding/
description: "Edit HTML in C# without changing its original encoding. Save a Windows-1252 file as bytes and see how new characters are written as HTML references."
version: "1.6.0"
---

# Edit HTML without changing its encoding 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/edit-html-without-changing-file-encoding/edit-html-without-changing-file-encoding.zip)

Read and save HTML as bytes. This example adds a coffee cup without converting the Windows-1252 file to UTF-8.

```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;

var doc = Document.Parse(
    File.ReadAllBytes("menu.html"));
var heading =
    doc.Root.QuerySelector("h1");
var edit = Edit.ReplaceText(
    heading, "Menu ☕");
var result = doc.Apply([edit]);
if (result.Document is not { } edited)
    throw new InvalidOperationException(
        result.Outcomes[0].Reason);
File.WriteAllBytes("edited.html",
    edited.ToLosslessBytes());
Console.WriteLine("Wrote edited.html");
```

Unzip [the example](https://recursiveai.org/onehtml/cookbook/edit-html-without-changing-file-encoding/edit-html-without-changing-file-encoding.zip), then `dotnet run`.

Prints `Wrote edited.html`. The input `menu.html` is included in the download and contains these lines, saved in Windows-1252 with CRLF line endings:

```html
<!doctype html>
<meta charset="windows-1252">
<title>Café</title>
<h1>Menu</h1>
<style>h1 { color: navy; }</style>
```

## The full program

The download edits the heading, then shows the bytes of `Café` in the output file, the literal heading markup, and the decoded heading text. It also tries the same character inside a `<style>` element on the original document, without writing that edit to disk.

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

var doc = Document.Parse(
    File.ReadAllBytes("menu.html"));
var heading =
    doc.Root.QuerySelector("h1");
var edit = Edit.ReplaceText(
    heading, "Menu ☕");
var result = doc.Apply([edit]);
if (result.Document is not { } edited)
    throw new InvalidOperationException(
        result.Outcomes[0].Reason);
File.WriteAllBytes("edited.html",
    edited.ToLosslessBytes());
Console.WriteLine("Wrote edited.html");

Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);
var windows1252 = Encoding.GetEncoding(1252);
var output = File.ReadAllBytes("edited.html");
Console.WriteLine($"Encoding: {edited.Source.Encoding.Name}");
var titleStart = output.AsSpan().IndexOf("<title>"u8) + "<title>".Length;
Console.WriteLine($"Title bytes: {Convert.ToHexString(output.AsSpan(titleStart, 4))}");
Console.WriteLine(windows1252.GetString(output).Split("\r\n").Single(
    line => line.StartsWith("<h1>")));
Console.WriteLine($"Text: {edited.Root.QuerySelector("h1").TextContent}");

var styleText = doc.Root.QuerySelector("style").FirstChild;
var rawEdit = doc.Apply([Edit.ReplaceText(styleText, "/* ☕ */")]);
Console.WriteLine($"Raw text edit: {rawEdit.Outcomes[0].Status}");
```

`dotnet run` prints:

```text
Wrote edited.html
Encoding: windows-1252
Title bytes: 436166E9
<h1>Menu &#x2615;</h1>
Text: Menu ☕
Raw text edit: Failed
```

The title’s `é` is still the single byte `E9`. The heading uses `&#x2615;`, a numeric character reference that the HTML parser reads back as `☕`. If the transaction returns no `Document`, don’t write a file; inspect `Outcomes` for the reason.

## Variations

Replace the `edit` line in the snippet at the top to put the character in an attribute rather than in the heading text:

```csharp
var edit = Edit.SetAttribute(
    heading, "title", "Coffee ☕");
```

The output heading is `<h1 title="Coffee &#x2615;">Menu</h1>`.

## Related recipes

- [Detect HTML encoding in C#](https://recursiveai.org/onehtml/cookbook/detect-encoding/)
- [Edit HTML without reformatting it](https://recursiveai.org/onehtml/cookbook/edit-html-csharp-lossless/)
- [Audit the byte ranges changed by HTML edits](https://recursiveai.org/onehtml/cookbook/audit-html-edit-byte-ranges/)

## The short answer

Read the original file with `File.ReadAllBytes`, give the bytes to `Document.Parse`, and apply your edit. Write `ToLosslessBytes()` from the successful result using `File.WriteAllBytes`. The edit encodes the replacement in the document’s encoding and copies the bytes outside rewritten ranges as-is. This avoids decoding a legacy file and then accidentally saving the whole thing in another encoding.

## How do you tell what encoding an HTML file uses?

The charset is the encoding used to interpret the file’s bytes as text. The parser checks a byte order mark first, then a supplied transport charset, then the HTML’s `<meta>` declaration, with Windows-1252 as the default. Read `doc.Source.Encoding.Name` to check what was chosen. If your HTML came from HTTP and the response has a charset, pass the response’s content type through `ParseOptions.ContentType` when parsing the bytes. A file saved to disk doesn’t carry that header, so keep it separately if the file relies on it.

The example declares `windows-1252` inside the file. Don’t guess the encoding from whether ASCII text such as the word `Menu` looks right. Those bytes have the same meaning in Windows-1252 and UTF-8, but bytes outside ASCII may not. Also don’t change `<meta charset>` as a way to convert the file. That edits the label, not the encoding used to write the edited bytes.

## How do HTML character references preserve characters outside Windows-1252?

A [numeric character reference](https://html.spec.whatwg.org/multipage/syntax.html#character-references) spells out a Unicode code point with characters the file can store. The cup `☕` is U+2615, so onehtml writes `&#x2615;` in ordinary text or an attribute value. Pass the cup itself to the edit, not the literal string `&#x2615;`: escaping that literal as ordinary text would display the reference instead of the cup.

Inside raw text such as `<style>`, the HTML parser does not decode character references. Writing `&#x2615;` there would change the content instead of preserving it. The library rejects the raw-text edit rather than replacing the cup with `?` or silently switching encoding. That is why the second operation in the download does not produce a new document.

## Does preserving encoding also preserve formatting?

They’re separate properties. A simple text or attribute change normally rewrites a small byte range. If that splice would change how the HTML parses, the editor can rewrite a larger region and check it again. Bytes outside the final rewritten regions stay the same, but markup inside a widened region can be reformatted. Inspect `ChangeSet.Ranges` and `Fallbacks` if you need to know exactly what was rewritten. The [editing docs](https://recursiveai.org/onehtml/docs/editing/) describe how the ranges are chosen and when a transaction fails instead.
