Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# Convert byte array to string, using preamble or default encoding

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?

like image 264
Christian Ernst Rysgaard Avatar asked Jun 12 '26 10:06

Christian Ernst Rysgaard


1 Answers

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*

like image 127
David M Avatar answered Jun 15 '26 00:06

David M



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!