views:

414

answers:

1

Im trying to convert a byte array to a string. The byte array includes a preamble (if the used encoder had one of those), and you must specify the default encoding if no preamble is stored in the byte array.

My code looks like this

public static string ArrayToStringUsingPreambleOrDefaultEncoder(byte[] bytes, Encoding defaultEncoder, out Encoding usedEncoder) {
  using (var mem = new MemoryStream(bytes))
  using (var reader = new StreamReader(mem, defaultEncoder, true)) {
    string result = reader.ReadToEnd();
    usedEncoder = reader.CurrentEncoding;
    return result;
  }
}

But it doesnt do the trick as I would expect. How do I make a StreamReader use the encoding specified by the preamble or a default encoding if no preamble is found. Do I really have to manually compare the preamble of ALL known encoders to the start of the array to find the right one?

+2  A: 

From MSDN: "StreamReader is designed for character input in a particular encoding". So yes, you really do need to sniff out the correct encoding from the preamble to do this. There's an example method to do this here:

http://www.personalmicrocosms.com/Pages/dotnettips.aspx?c=15&t=17

David M
broken link, where is the code, please ??
Alhambra Eidos