Michael Dorgan
Michael Dorgan

Reputation: 12515

StreamReader fails to detect BOM

I have the following piece of code:

using (StreamReader sr = new StreamReader(path, Encoding.GetEncoding("shift-jis"), true)) {
    mCertainFileIsUTFFormat = !sr.CurrentEncoding.Equals(Encoding.GetEncoding("shift-jis"));
    mCodingFromBOM = sr.CurrentEncoding;

    String line = sr.ReadToEnd();
    return line.Split('\n');
}

Basically reading a file and assuming Shift-Jis if there is no BOM. Alas, this method is always, no matter what, returning Shift-JIS encoding, even if the file in question has a BOM within it. Am I doing something wrong here or perhaps there is a known issue? I could always open the file binary and do the work myself, but this is supposed to do what I want :)

Upvotes: 0

Views: 716

Answers (1)

Alexei Levenkov
Alexei Levenkov

Reputation: 100545

You need to call Read of any kind - StreamReader will not detect encoding before reading. I.e. get encoding after your ReadToEnd call:

  String line = sr.ReadToEnd();
  mCodingFromBOM = sr.CurrentEncoding;

Info: StreamReader.CurrentEncoding

The value can be different after the first call to any Read` method of StreamReader, since encoding autodetection is not done until the first call to a Read method.

Upvotes: 6

Related Questions