代码之家  ›  专栏  ›  技术社区  ›  AndreyAkinshin

C#[重复]中的自动编码检测

  •  3
  • AndreyAkinshin  · 技术社区  · 15 年前


    Determine a string's encoding in C#

    许多文本编辑器(如Notepad++)可以检测任意文件的编码。我能在C#中检测文件的编码吗?

    1 回复  |  直到 8 年前
        1
  •  9
  •   Darin Dimitrov    15 年前

    A StreamReader 在尝试读取时,如果有BOM表,将尝试自动检测文件的编码:

    public class Program
    {
        static void Main(string[] args)
        {
            using (var reader = new StreamReader("foo.txt"))
            {
                // Make sure you read from the file or it won't be able
                // to guess the encoding
                var file = reader.ReadToEnd();
                Console.WriteLine(reader.CurrentEncoding);
            }
        }
    }
    
    推荐文章