How to read byte[] with current encoding using streamreader

25,995

A file has no encoding. A byte array has no encoding. A byte has no encoding. Encoding is something that transforms bytes to text and vice versa.

What you see in text editors and the like is actually program magic: The editor tries out different encodings an then guesses which one makes the most sense. This is also what you enable with the boolean parameter. If this does not produce what you want, then this magic fails.

var reader = new StreamReader(new MemoryStream(data), Encoding.Default);

will use the OS/Location specific default encoding. If that is still not what you want, then you need to be completely explicit, and tell the streamreader what exact encoding to use, for example (just as an example, you said you did not want UTF8):

var reader = new StreamReader(new MemoryStream(data), Encoding.UTF8);
Share:
25,995
Ori
Author by

Ori

Updated on December 05, 2020

Comments

  • Ori
    Ori over 3 years

    I would like to read byte[] using C# with the current encoding of the file.

    As written in MSDN the default encoding will be UTF-8 when the constructor has no encoding:

    var reader = new StreamReader(new MemoryStream(data)).
    

    I have also tried this, but still get the file as UTF-8:

    var reader = new StreamReader(new MemoryStream(data),true)
    

    I need to read the byte[] with the current encoding.

  • Ori
    Ori almost 11 years
    I have checked again what exactly we get in the web-service call and it is byte[]. as i understand from the answers i cannot know the encoding of the data. then i will need to check if the file contains bom or diacritic in order to select the correct encoding.(utf-8,utf-8 with bom or 1252). thank you for all the answers.