How to find out the Encoding of a File? C#

Viewed 29477

Well i need to find out which of the files i found in some directory is UTF8 Encoded either ANSI encoded to change the Encoding in something else i decide later. My problem is.. how can i find out if a file is UTF8 or ANSI Encoded? Both of the encodings are actually posible in my files.

5 Answers
   public static System.Text.Encoding GetEncoding(string filepath, Encoding defaultEncoding)
    {
        // will fall to defaultEncoding if file does not have BOM

        using (var reader = new StreamReader(filepath, defaultEncoding, true))
        {
            reader.Peek(); //need it
            return reader.CurrentEncoding;
        }
    }

Check Byte Order Mark (BOM).

To see the BOM you need to see file in a hexadecimal view.

Notepad show the file encoding at status bar, but it can be just estimated, if the file hasn't the BOM set.

Related