I am being sent text files saved in ISO 88591-1 format that contain accented characters from the Latin-1 range (as well as normal ASCII a-z, etc.). How do I convert these files to UTF-8 using C# so that the single-byte accented characters in ISO 8859-1 become valid UTF-8 characters?
I have tried to use a StreamReader with ASCIIEncoding, and then converting the ASCII string to UTF-8 by instantiating encoding ascii and encoding utf8 and then using Encoding.Convert(ascii, utf8, ascii.GetBytes( asciiString) ) — but the accented characters are being rendered as question marks.
What step am I missing?
You need to get the proper
Encodingobject. ASCII is just as it’s named: ASCII, meaning that it only supports 7-bit ASCII characters. If what you want to do is convert files, then this is likely easier than dealing with the byte arrays directly.However, if you want to have the byte arrays yourself, it’s easy enough to do with
Encoding.Convert.It’s important to note here, however, that if you want to go down this road then you should not use an encoding-based string reader like
StreamReaderfor your file IO.FileStreamwould be better suited, as it will read the actual bytes of the files.In the interest of fully exploring the issue, something like this would work:
In this example, the
buffervariable gets filled with the actual data in the file as abyte[], so no conversion is done.Encoding.Convertspecifies a source and destination encoding, then stores the converted bytes in the variable named…converted. This is then written to the output file directly.Like I said, the first option using
StreamReaderandStreamWriterwill be much simpler if this is all you’re doing, but the latter example should give you more of a hint as to what’s actually going on.