c# - 查找任何文件编码的有效方法

标签 c# encoding

是的是最常见的问题,这件事对我来说很模糊,因为我对此了解不多。

但我想要一种非常精确的方法来查找文件编码。 像 Notepad++ 一样精确。

最佳答案

StreamReader.CurrentEncoding 属性很少为我返回正确的文本文件编码。通过分析文件的字节顺序标记 (BOM),我在确定文件的字节顺序方面取得了更大的成功。如果文件没有 BOM,则无法确定文件的编码。

*更新 4/08/2020 以包括 UTF-32LE 检测并返回 UTF-32BE 的正确编码

/// <summary>
/// Determines a text file's encoding by analyzing its byte order mark (BOM).
/// Defaults to ASCII when detection of the text file's endianness fails.
/// </summary>
/// <param name="filename">The text file to analyze.</param>
/// <returns>The detected encoding.</returns>
public static Encoding GetEncoding(string filename)
{
    // Read the BOM
    var bom = new byte[4];
    using (var file = new FileStream(filename, FileMode.Open, FileAccess.Read))
    {
        file.Read(bom, 0, 4);
    }

    // Analyze the BOM
    if (bom[0] == 0x2b && bom[1] == 0x2f && bom[2] == 0x76) return Encoding.UTF7;
    if (bom[0] == 0xef && bom[1] == 0xbb && bom[2] == 0xbf) return Encoding.UTF8;
    if (bom[0] == 0xff && bom[1] == 0xfe && bom[2] == 0 && bom[3] == 0) return Encoding.UTF32; //UTF-32LE
    if (bom[0] == 0xff && bom[1] == 0xfe) return Encoding.Unicode; //UTF-16LE
    if (bom[0] == 0xfe && bom[1] == 0xff) return Encoding.BigEndianUnicode; //UTF-16BE
    if (bom[0] == 0 && bom[1] == 0 && bom[2] == 0xfe && bom[3] == 0xff) return new UTF32Encoding(true, true);  //UTF-32BE

    // We actually have no idea what the encoding is if we reach this point, so
    // you may wish to return null instead of defaulting to ASCII
    return Encoding.ASCII;
}

关于c# - 查找任何文件编码的有效方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3825390/

相关文章:

c# - Y型任务执行

iphone - Unicode 字符未显示

c# - 如何使用带有 C# 的 .NET MVC 从配置文件中的列表中引用特定对象

c# - wpf 单选按钮已选中 "Index was out of range. Must be non-negative and less than the size of the collection."

C# Windows 窗体 - 如何根据背景颜色的深浅更改选项卡页标题文本颜色?

c# - 检查字符串不为空、不为空且不为 "0000"的最简单方法是什么?

python - 字节串怎样才能很好的存储呢? - 不可 JSON 序列化 -

javascript - eclipse : can't remove default encoding for javascript and json

c++ - Base 64 编码丢失数据

c# - 将字符串转换为字节数组,反之亦然