views:

1056

answers:

3
+3  Q: 

C# read unicode?

Hi.

I am receiving a unicode message via the network, which looks like:

74 00 65 00 73 00 74 00 3F 00

I am using a BinaryReader to read the stream from my socket, but the problem is that it doesn't offer a "ReadWideString" function, or something similar to it. Anyone an idea how to deal with this?

Thanks!

+6  A: 

Strings in C# are Unicode by default. Try

string converted = Encoding.Unicode.GetString(data);

where data is a byte[] array containing your Unicode data. If your data is big endian, you can try

string converted = Encoding.BigEndianUnicode.GetString(data);
Charlie Salts
Each byte every 2 is equal to 0, it's rather unlikely that it's utf-8.
Ravadre
+8  A: 

Simple!

string str = System.Text.Encoding.Unicode.GetString(array);

where array is your array of bytes.

Dmitry Brant
Thanks! Got it working, thanks to others too.
+3  A: 

You could use a StreamReader like this:

StreamReader sr = new StreamReader(stream, Encoding.Unicode);

If your stream only contains lines of text then StreamReader is more suitable than BinaryReader. If your string is embedded inside binary data then it is probably better to decode the string using the Encoding.GetString method as others have suggested

Martin Liversage