3

Possible Duplicate:
byte[] to string in c#

I have an byte array read from a stream. I'd like to convert it to a string.

This worked for me:

var str= new string(bytearr.Select(x=>(char)x).ToArray());

But I feel there's a better way to do it? Is there?

Community
  • 1
  • 1
Andrzej Gis
  • 13,706
  • 14
  • 86
  • 130

5 Answers5

14
Encoding.UTF8.GetString(bytearr);

You will need to know the correct encoding and use that, UTF8 is just an example. Based on what worked for you, I will guess that you either have UTF8 or ASCII.

driis
  • 161,458
  • 45
  • 265
  • 341
  • This does **not** seem like a UTF-8 encoded stream. For example the string `naïve` in UTF-8 would be `6E - 61 - C3 AF - 76 - 65`. Note that the number of `char` does not correspond to the number of bytes (because `'ï'` takes two bytes). So I would say he should use `Encoding.ASCII` or maybe something like `Encoding.GetEncoding(1252)` (if he knows what Windows codepage (like 1252 "Western European (Windows)") to use; will work well with `naïve`). – Jeppe Stig Nielsen Jan 04 '13 at 23:14
  • @JeppeStigNielsen, correct, the point is that the OP code is not safe, and that he needs to know the encoding. Since ASCII and UTF8 are exactly the same below codepoint 128, the UTF8 solution works both for plain ASCII (without the character extensions) _and_ it accounts for the possibility that the text is actually UTF-8. – driis Jan 05 '13 at 10:00
2

You could use the built-in functions from Encoding:

string myString = Encoding.UTF8.GetString(bytearr);

http://msdn.microsoft.com/en-us/library/aa332098(v=vs.71).aspx

Foggzie
  • 9,691
  • 1
  • 31
  • 48
1
var str = System.Text.Encoding.UTF8.GetString(byte[])
Rob
  • 1,071
  • 8
  • 10
1

you could just use System.Text.Encoding

string result = Encoding.UTF8.GetString(bytearr);
sa_ddam213
  • 42,848
  • 7
  • 101
  • 110
0

You should use the instance of Encoding

from msdn

public UTF8Encoding(
    bool encoderShouldEmitUTF8Identifier,
    bool throwOnInvalidBytes
)

Parameters

encoderShouldEmitUTF8Identifier

Type: System.Boolean true to specify that a Unicode byte order mark is provided; otherwise, false.

throwOnInvalidBytes

Type: System.Boolean

true to specify that an exception be thrown when an invalid encoding is detected; otherwise, false.

so Use

   var encoding = new UTF8Encoding(false,true);

encoding.GetString (byteArr);
Dan Hunex
  • 5,172
  • 2
  • 27
  • 38