3

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?

1 Answer 1

2

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

Edit: The above link is broken but the old page is available at Wayback Machine Internet Archive: https://web.archive.org/web/20090203034127/http://www.personalmicrocosms.com/Pages/dotnettips.aspx?c=15&t=17*

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.