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?

0

5 Answers 5

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.

Sign up to request clarification or add additional context in comments.

2 Comments

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).
@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.
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

Comments

1
var str = System.Text.Encoding.UTF8.GetString(byte[])

Comments

1

you could just use System.Text.Encoding

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

Comments

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.