The zip’s UTF-16 config.yaml contains label: Café 東京.
dotnet add package OneYamlWorks on .NET 8, 9, and 10.
using OneYaml; using var input = File.OpenRead("config.yaml"); using var doc = YamlDocument.Parse(input); Console.WriteLine(doc.Get<string>("/label"));
Prints the label:
Café 東京Invalid YAML throws YamlException.
Unzip the example, then dotnet run.
Variations
To send the same YAML to a tool that expects UTF-8, use ToUtf8Bytes(). This variation prints the decoded UTF-8 YAML rather than just its label:
using System.Text; using OneYaml; using var input = File.OpenRead("config.yaml"); using var doc = YamlDocument.Parse(input); Console.Write(Encoding.UTF8.GetString(doc.ToUtf8Bytes()));
label: Café 東京Related recipes
The short answer
Open the YAML file with File.OpenRead and pass the resulting stream to YamlDocument.Parse. For the included UTF-16 sample, OneYaml reads the byte order mark before decoding. doc.Get<string>("/label") then returns the label as a C# string without losing the accents or Japanese characters.
How do I read a UTF-16 YAML file in C# without specifying the encoding?
Start with a stream of bytes rather than text decoded with a guessed encoding. A byte order mark is a prefix that identifies an encoding and, for UTF-16, which byte comes first. The sample starts with FF FE, the UTF-16 little-endian mark. Those bytes aren’t part of the label key or its value.
The OneYaml editing guide lists UTF-8, UTF-16, and UTF-32 detection from a byte order mark or the first characters. If you already have a correctly decoded C# string, parse that string instead. If the text contains replacement characters because it was decoded incorrectly, reopen the original bytes; parsing the string cannot recover them.
What’s the difference between UTF-8 and UTF-16 when writing YAML back?
They represent the same characters with different bytes. Reading Café 東京 into a C# string is the same task either way, but when you write the YAML byte stream back, choose the encoding the next reader expects. ToBytes() and WriteTo(...) retain the source encoding and byte order mark. Choose those when updating a file that another tool expects to stay UTF-16. Use ToUtf8Bytes() when the next tool expects UTF-8, as in the variation. Neither choice requires changing the YAML keys or values.