I am trying to convert an array of bytes to a string. The byte array includes the preamble (if the encoder used has one of them), and you must specify the default encoding if the preamble is not stored in the byte array.
My code is as follows
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 this does not do the trick as I expected. How to force StreamReader to use the encoding specified in the preamble or by default if the preamble is not found. Do I really need to manually compare the preamble of all known encoders to the beginning of the array to find the correct one?
source
share