ILoveFoo
ILoveFoo

Reputation:

C# read unicode?

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!

Upvotes: 7

Views: 20057

Answers (3)

Martin Liversage
Martin Liversage

Reputation: 106916

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

Upvotes: 6

Dmitry Brant
Dmitry Brant

Reputation: 7719

Simple!

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

where array is your array of bytes.

Upvotes: 16

Charlie Salts
Charlie Salts

Reputation: 13498

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);

Upvotes: 8

Related Questions