1

While parsing certain documents, I get the character code 146, which is actually an ANSI number. While writing the char to text file, nothing is shown. If we write the char as Unicode number- 8217, the character is displayed fine.

Can anyone give me advice on how to convert the ANSI number 146 to Unicode 8217 in C#.

reference: http://www.alanwood.net/demos/ansi.html

Thanks

1
  • Are you reading files? You can set the encoding as you open the file for reading...
    – tofutim
    Commented May 31, 2011 at 7:21

2 Answers 2

8

"ANSI" is really a misnomer - there are many encodings often known as "ANSI". However, if you're sure you need code page 1252, you can use:

Encoding encoding = Encoding.GetEncoding(1252);
using (TextReader reader = File.OpenText(filename, encoding))
{
    // Read text and use it
}

or

Encoding encoding = Encoding.GetEncoding(1252);
string text = File.ReadAllText(filename, encoding);

That's for reading a file - writing a file is the same idea. Basically when you're converting from binary (e.g. file contents) to text, use an appropriate Encoding object.

4
  • HI Jon, Thank you for the details. Actually, I get only the character code (146) from a document and it is a PDF document and not a text file. Thereby I need to convert the code to corresponding text. So, could you please give me an idea on how to convert the code say, 146 to 8712, instead of using the TextReader class.
    – user438959
    Commented May 31, 2011 at 8:43
  • @user438959: It's not really clear what you mean. The PDF reader should take care of the encoding for you. If it's applying the wrong encoding, it's basically too late - you can easily have lost data already.
    – Jon Skeet
    Commented May 31, 2011 at 9:01
  • I am extracting the text from the PDF. The encoding of the character is winansi encoding and the character code is 146 (right singe quotation mark). How can I write the character to a text file having only the character code (146).
    – user438959
    Commented May 31, 2011 at 9:07
  • @user438959: It's still not clear what you mean. When you say "the character code" do you mean you've got the data correctly as a Unicode string and want to just write it to a CP-1252 text file, or you're having trouble reading it correctly?
    – Jon Skeet
    Commented May 31, 2011 at 22:27
3

My recommendation would be to read Joel's "Absolute Minimum Every Software Developer Must Know About Unicode and Character Sets. There's quite a lot involved in your question and my experience has been that you'll just struggle against the simple answers if you don't understand these basics. It takes around 15 minutes to read.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.