Programming Microsoft Windows with C#

Windows-Compatible Character Encoding

In Appendix A, pages 1194 through 1196, I discuss character encoding in the StreamWriter class. After I had completed the book, I discovered another approach that may be of value. The paragraph that follows is adapted from my book Programming Microsoft Windows with Microsoft Visual Basic .NET. It should appear right before the last paragraph on page 1196:

So what do you do if you have character strings that contain only characters from the Windows ANSI character set (characters 0x00 through 0xFF) and you want to write these strings to a file in a one-byte-per-character format? You can't use Encoding.ASCII because characters 0x80 through 0xFF will be replaced by question marks. And you can't use Encoding.UTF8 because characters 0x80 through 0xFF will be written to the file as a pair of bytes. In such a case you need to obtain an Encoding objecting using the static GetEncoding method of the Encoding class with an argument of 1252 (the code page identifier for the Windows character set). This is the argument you pass to the StreamWriter constructor:

© Charles Petzold, 2003
cp@charlespetzold.com
This page last updated March, 2003