A set of technologies in .NET for building web applications and web services. Miscellaneous topics that do not fit into specific categories.
Hi,
Since this thread has already provided a lot of insights, I would like to give a better summarization of this problem and the approach to solve it.
This problem occurs because the text file being read contains characters (such as en-dash, em-dash, curly quotes, etc.) that are not part of ASCII. The file itself was originally saved in a single-byte code page (often Windows-1252 / “ANSI”). When it’s read without explicitly specifying the correct encoding and then written out with a different one (e.g., Unicode/UTF-16), the characters are misinterpreted and show up incorrectly.
In short:
- Mismatched encodings cause the corruption: reading with one code page, writing with another.
- ASCII cannot represent extended symbols like en-dash or curly quotes.
- .NET’s
File.ReadAllTextdefaults to UTF-8 in .NET Core/.NET 5+ and to the system ANSI code page in older .NET Framework apps, so behavior may differ across environments.
Ways to Resolve
- Read/Write with the Correct Legacy Encoding
If your file was created in Windows-1252 (ANSI), explicitly specify that when reading/writing:
Encoding.RegisterProvider(CodePagesEncodingProvider.Instance); string input = File.ReadAllText("input.txt", Encoding.GetEncoding(1252)); File.WriteAllText("output.txt", input, Encoding.GetEncoding(1252)); - Migrate to Unicode (Recommended)
After detecting the correct source encoding, convert to UTF-8 or UTF-16 to ensure all characters are preserved consistently:
string input = File.ReadAllText("input.txt", Encoding.GetEncoding(1252)); File.WriteAllText("output.txt", input, Encoding.UTF8); - Avoid
Encoding.DefaultSince it varies by OS and runtime, relying on the default encoding can lead to inconsistent results across machines.
In conclusion: either use the same encoding for both reading and writing (e.g., Windows-1252) or convert your files to a Unicode encoding like UTF-8 for future use.
Hope this helps.