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

后端 未结 5 921
感情败类
感情败类 2020-12-01 10:56

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

5条回答
  •  误落风尘
    2020-12-01 11:27

       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.

提交回复
热议问题