3

How do I print out the value of a unicode String in C# to the console?

byte[] unicodeBytes = new byte[] 
    {0x61, 0x70, 0x70, 0x6C, 0x69, 0x63, 0x61, 
     0x74, 0x69, 0x6F, 0x6E, 0x2F, 0x70, 0x63, 
     0x61, 0x70};

string unicodeString = Encoding.Unicode.GetString(unicodeBytes);

Console.WriteLine(unicodeString);

What I get for the above is "?????????"

However, I see the following in the autos and local window when in debug mode for the value of unicodeString which is what I wanted to display.

"慒䑷瑡彡〵〶ㅟ⸷慣�"

How do I print out the correct result to the console as what the autos and local window for debugging demonstrated?

Lopper
  • 3,499
  • 7
  • 38
  • 57
  • It is an 8-bit encoding, not Unicode. Could be a lot of them (well, about all of them), but Encoding.ASCII.GetString() will work fine since they are all ASCII codes. – Hans Passant Apr 14 '10 at 17:25
  • This may help http://stackoverflow.com/questions/2492077/output-unicode-strings-in-windows-console-app – CDSO1 Apr 14 '10 at 16:00

2 Answers2

3

I suspect these bytes are really in UTF8, not in UTF16 as you supposed.

See, if you change your code to:

byte[] unicodeBytes = new byte[] 
    {0x61, 0x70, 0x70, 0x6C, 0x69, 0x63, 0x61, 
     0x74, 0x69, 0x6F, 0x6E, 0x2F, 0x70, 0x63, 
     0x61, 0x70};

string unicodeString = Encoding.UTF8.GetString(unicodeBytes);

Console.WriteLine(unicodeString);

You'll get the output:

application/pcap

Oleks
  • 31,955
  • 11
  • 77
  • 132
1

Please see the following answer: c# unicode string output

In short:

Console.OutputEncoding = Encoding.UTF8;

Then change the console font to Lucida Console, which supports unicode characters.

Community
  • 1
  • 1
Josh Gallagher
  • 5,211
  • 2
  • 33
  • 60