【问题标题】:Determine a string's encoding in C#在 C# 中确定字符串的编码
【发布时间】:2010-11-04 18:00:01
【问题描述】:

有什么方法可以确定 C# 中字符串的编码方式吗?

说,我有一个文件名字符串,但我不知道它是用 Unicode UTF-16 编码还是系统默认编码,我该如何找到?

【问题讨论】:

  • 您不能在 Unicode 中“编码”。并且没有任何其他先验信息,无法自动确定 any 给定字符串的编码。
  • 也许更清楚一点:您使用“编码”方案(utf-,iso- i>、big5、shift-jis 等),然后您将字符集的字节字符串解码为 Unicode。您不使用 Unicode 编码字节串。您不会在字节串中解码 Unicode。
  • @NicDunZ - 编码本身(特别是 UTF-16)也通常称为“Unicode”。对与错,这就是生活。即使在 .NET 中,请查看 Encoding.Unicode - 表示 UTF-16。
  • 哦,好吧,我不知道 .NET 如此具有误导性。这看起来像是一个可怕的学习习惯。对不起@krebstar,这不是我的意图(我仍然认为你编辑的问题现在比以前更有意义)
  • @Nicdumz #1:有一种方法可以概率性地确定要使用的编码。看看 IE(现在还有 FF with View - Character Encoding - Auto-detect)对此做了什么:它尝试一种编码,看看它是否可能是“写得好”或更改它并再次尝试.来吧,这会很有趣!

标签: c# string encoding


【解决方案1】:

以下代码具有以下特点:

  1. 检测或尝试检测 UTF-7、UTF-8/16/32(bom、no bom、little & big endian)
  2. 如果未找到 Unicode 编码,则回退到本地默认代码页。
  3. 检测(很有可能)缺少 BOM/签名的 unicode 文件
  4. 在文件中搜索 charset=xyz 和 encoding=xyz 以帮助确定编码。
  5. 要节省处理,您可以“品尝”文件(可定义字节数)。
  6. 返回编码和解码的文本文件。
  7. 纯粹基于字节的效率解决方案

正如其他人所说,没有解决方案是完美的(当然,人们无法轻易区分全球使用的各种 8 位扩展 ASCII 编码),但我们可以得到“足够好”,特别是如果开发人员也提供给用户一个替代编码列表,如下所示:What is the most common encoding of each language?

可以使用Encoding.GetEncodings();找到完整的编码列表

// Function to detect the encoding for UTF-7, UTF-8/16/32 (bom, no bom, little
// & big endian), and local default codepage, and potentially other codepages.
// 'taster' = number of bytes to check of the file (to save processing). Higher
// value is slower, but more reliable (especially UTF-8 with special characters
// later on may appear to be ASCII initially). If taster = 0, then taster
// becomes the length of the file (for maximum reliability). 'text' is simply
// the string with the discovered encoding applied to the file.
public Encoding detectTextEncoding(string filename, out String text, int taster = 1000)
{
    byte[] b = File.ReadAllBytes(filename);

    //////////////// First check the low hanging fruit by checking if a
    //////////////// BOM/signature exists (sourced from http://www.unicode.org/faq/utf_bom.html#bom4)
    if (b.Length >= 4 && b[0] == 0x00 && b[1] == 0x00 && b[2] == 0xFE && b[3] == 0xFF) { text = Encoding.GetEncoding("utf-32BE").GetString(b, 4, b.Length - 4); return Encoding.GetEncoding("utf-32BE"); }  // UTF-32, big-endian 
    else if (b.Length >= 4 && b[0] == 0xFF && b[1] == 0xFE && b[2] == 0x00 && b[3] == 0x00) { text = Encoding.UTF32.GetString(b, 4, b.Length - 4); return Encoding.UTF32; }    // UTF-32, little-endian
    else if (b.Length >= 2 && b[0] == 0xFE && b[1] == 0xFF) { text = Encoding.BigEndianUnicode.GetString(b, 2, b.Length - 2); return Encoding.BigEndianUnicode; }     // UTF-16, big-endian
    else if (b.Length >= 2 && b[0] == 0xFF && b[1] == 0xFE) { text = Encoding.Unicode.GetString(b, 2, b.Length - 2); return Encoding.Unicode; }              // UTF-16, little-endian
    else if (b.Length >= 3 && b[0] == 0xEF && b[1] == 0xBB && b[2] == 0xBF) { text = Encoding.UTF8.GetString(b, 3, b.Length - 3); return Encoding.UTF8; } // UTF-8
    else if (b.Length >= 3 && b[0] == 0x2b && b[1] == 0x2f && b[2] == 0x76) { text = Encoding.UTF7.GetString(b,3,b.Length-3); return Encoding.UTF7; } // UTF-7

        
    //////////// If the code reaches here, no BOM/signature was found, so now
    //////////// we need to 'taste' the file to see if can manually discover
    //////////// the encoding. A high taster value is desired for UTF-8
    if (taster == 0 || taster > b.Length) taster = b.Length;    // Taster size can't be bigger than the filesize obviously.


    // Some text files are encoded in UTF8, but have no BOM/signature. Hence
    // the below manually checks for a UTF8 pattern. This code is based off
    // the top answer at: https://stackoverflow.com/questions/6555015/check-for-invalid-utf8
    // For our purposes, an unnecessarily strict (and terser/slower)
    // implementation is shown at: https://stackoverflow.com/questions/1031645/how-to-detect-utf-8-in-plain-c
    // For the below, false positives should be exceedingly rare (and would
    // be either slightly malformed UTF-8 (which would suit our purposes
    // anyway) or 8-bit extended ASCII/UTF-16/32 at a vanishingly long shot).
    int i = 0;
    bool utf8 = false;
    while (i < taster - 4)
    {
        if (b[i] <= 0x7F) { i += 1; continue; }     // If all characters are below 0x80, then it is valid UTF8, but UTF8 is not 'required' (and therefore the text is more desirable to be treated as the default codepage of the computer). Hence, there's no "utf8 = true;" code unlike the next three checks.
        if (b[i] >= 0xC2 && b[i] < 0xE0 && b[i + 1] >= 0x80 && b[i + 1] < 0xC0) { i += 2; utf8 = true; continue; }
        if (b[i] >= 0xE0 && b[i] < 0xF0 && b[i + 1] >= 0x80 && b[i + 1] < 0xC0 && b[i + 2] >= 0x80 && b[i + 2] < 0xC0) { i += 3; utf8 = true; continue; }
        if (b[i] >= 0xF0 && b[i] < 0xF5 && b[i + 1] >= 0x80 && b[i + 1] < 0xC0 && b[i + 2] >= 0x80 && b[i + 2] < 0xC0 && b[i + 3] >= 0x80 && b[i + 3] < 0xC0) { i += 4; utf8 = true; continue; }
        utf8 = false; break;
    }
    if (utf8 == true) {
        text = Encoding.UTF8.GetString(b);
        return Encoding.UTF8;
    }


    // The next check is a heuristic attempt to detect UTF-16 without a BOM.
    // We simply look for zeroes in odd or even byte places, and if a certain
    // threshold is reached, the code is 'probably' UF-16.          
    double threshold = 0.1; // proportion of chars step 2 which must be zeroed to be diagnosed as utf-16. 0.1 = 10%
    int count = 0;
    for (int n = 0; n < taster; n += 2) if (b[n] == 0) count++;
    if (((double)count) / taster > threshold) { text = Encoding.BigEndianUnicode.GetString(b); return Encoding.BigEndianUnicode; }
    count = 0;
    for (int n = 1; n < taster; n += 2) if (b[n] == 0) count++;
    if (((double)count) / taster > threshold) { text = Encoding.Unicode.GetString(b); return Encoding.Unicode; } // (little-endian)


    // Finally, a long shot - let's see if we can find "charset=xyz" or
    // "encoding=xyz" to identify the encoding:
    for (int n = 0; n < taster-9; n++)
    {
        if (
            ((b[n + 0] == 'c' || b[n + 0] == 'C') && (b[n + 1] == 'h' || b[n + 1] == 'H') && (b[n + 2] == 'a' || b[n + 2] == 'A') && (b[n + 3] == 'r' || b[n + 3] == 'R') && (b[n + 4] == 's' || b[n + 4] == 'S') && (b[n + 5] == 'e' || b[n + 5] == 'E') && (b[n + 6] == 't' || b[n + 6] == 'T') && (b[n + 7] == '=')) ||
            ((b[n + 0] == 'e' || b[n + 0] == 'E') && (b[n + 1] == 'n' || b[n + 1] == 'N') && (b[n + 2] == 'c' || b[n + 2] == 'C') && (b[n + 3] == 'o' || b[n + 3] == 'O') && (b[n + 4] == 'd' || b[n + 4] == 'D') && (b[n + 5] == 'i' || b[n + 5] == 'I') && (b[n + 6] == 'n' || b[n + 6] == 'N') && (b[n + 7] == 'g' || b[n + 7] == 'G') && (b[n + 8] == '='))
            )
        {
            if (b[n + 0] == 'c' || b[n + 0] == 'C') n += 8; else n += 9;
            if (b[n] == '"' || b[n] == '\'') n++;
            int oldn = n;
            while (n < taster && (b[n] == '_' || b[n] == '-' || (b[n] >= '0' && b[n] <= '9') || (b[n] >= 'a' && b[n] <= 'z') || (b[n] >= 'A' && b[n] <= 'Z')))
            { n++; }
            byte[] nb = new byte[n-oldn];
            Array.Copy(b, oldn, nb, 0, n-oldn);
            try {
                string internalEnc = Encoding.ASCII.GetString(nb);
                text = Encoding.GetEncoding(internalEnc).GetString(b);
                return Encoding.GetEncoding(internalEnc);
            }
            catch { break; }    // If C# doesn't recognize the name of the encoding, break.
        }
    }


    // If all else fails, the encoding is probably (though certainly not
    // definitely) the user's local codepage! One might present to the user a
    // list of alternative encodings as shown here: https://stackoverflow.com/questions/8509339/what-is-the-most-common-encoding-of-each-language
    // A full list can be found using Encoding.GetEncodings();
    text = Encoding.Default.GetString(b);
    return Encoding.Default;
}

【讨论】:

  • 这适用于西里尔文(可能还有其他所有).eml 文件(来自邮件的字符集标题)
  • UTF-7 实际上不能这么天真地解码;它的完整前导码更长,并且包括第一个字符的两位。 .Net 系统似乎根本不支持 UTF7 的序言系统。
  • 当我检查的其他方法都没有帮助时为我工作!谢谢丹。
  • 感谢您的解决方案。我用它来确定来自完全不同来源的文件的编码。但我发现,如果我使用太低的品尝器值,结果可能是错误的。 (例如,代码为 UTF8 文件返回 Encoding.Default,即使我使用 b.Length / 10 作为我的品尝器。)所以我想知道,使用小于 b.Length 的品尝器的论据是什么?看来我只能得出结论,当且仅当我扫描了整个文件时,Encoding.Default 是可以接受的。
  • @Sean:它适用于速度比准确性更重要的情况,尤其是对于可能有数十或数百兆字节大小的文件。根据我的经验,即使是较低的品尝者值也可以在大约 99.9% 的时间内产生正确的结果。您的体验可能会有所不同。
【解决方案2】:

这取决于字符串“来自”的位置。 .NET 字符串是 Unicode (UTF-16)。如果您将数据库中的数据读取到字节数组中,则可能会有所不同。

可能对这篇 CodeProject 文章感兴趣:Detect Encoding for in- and outgoing text

Jon Skeet 的 Strings in C# and .NET 是对 .NET 字符串的出色解释。

【讨论】:

  • 它来自一个非 Unicode C++ 应用程序。CodeProject 文章似乎有点过于复杂,但它似乎可以做我想做的事情。谢谢..
【解决方案3】:

查看 Utf8Checker,它是一个在纯托管代码中完全执行此操作的简单类。 http://utf8checker.codeplex.com

注意:正如已经指出的那样,“确定编码”仅对字节流有意义。如果您有一个字符串,那么它已经被沿途的某个人编码,该人已经知道或猜到了编码以首先获取该字符串。

【讨论】:

  • 如果字符串是使用简单的 8 位编码完成的不正确解码,并且您有用于解码它的编码,您 可以 通常可以在没有任何损坏的情况下取回字节,不过。
  • 链接烂在这个答案上
【解决方案4】:

我知道这有点晚了 - 但要清楚:

字符串实际上没有编码...在.NET 中,字符串是 char 对象的集合。本质上,如果它是一个字符串,它已经被解码了。

但是,如果您正在读取由字节组成的文件的内容,并希望将其转换为字符串,则必须使用文件的编码。

.NET 包括以下编码和解码类:ASCII、UTF7、UTF8、UTF32 等。

这些编码中的大多数都包含某些字节顺序标记,可用于区分所使用的编码类型。

.NET 类 System.IO.StreamReader 能够通过读取这些字节顺序标记来确定流中使用的编码;

这是一个例子:

    /// <summary>
    /// return the detected encoding and the contents of the file.
    /// </summary>
    /// <param name="fileName"></param>
    /// <param name="contents"></param>
    /// <returns></returns>
    public static Encoding DetectEncoding(String fileName, out String contents)
    {
        // open the file with the stream-reader:
        using (StreamReader reader = new StreamReader(fileName, true))
        {
            // read the contents of the file into a string
            contents = reader.ReadToEnd();

            // return the encoding.
            return reader.CurrentEncoding;
        }
    }

【讨论】:

  • 这不适用于检测没有 BOM 的 UTF 16。如果它未能检测到任何 unicode 编码,它也不会退回到用户的本地默认代码页。您可以通过将 Encoding.Default 添加为 StreamReader 参数来修复后者,但是如果没有 BOM,代码将无法检测到 UTF8。
  • @DanW:没有 BOM 的 UTF-16 真的做过吗?我永远不会使用它;打开几乎任何东西都注定是一场灾难。
【解决方案5】:

另一种选择,来晚了,抱歉:

http://www.architectshack.com/TextFileEncodingDetector.ashx

这个仅 C# 的小型类使用 BOMS(如果存在),否则会尝试自动检测可能的 Unicode 编码,如果没有任何 Unicode 编码可能或不可能,则回退。

听起来上面引用的 UTF8Checker 做了类似的事情,但我认为这在范围上稍微宽泛一些 - 而不仅仅是 UTF8,它还检查可能缺少 BOM 的其他可能的 Unicode 编码(UTF-16 LE 或 BE) .

希望这对某人有所帮助!

【讨论】:

  • 相当不错的代码,它解决了我的编码检测问题:)
【解决方案6】:

SimpleHelpers.FileEncoding Nuget 包将 C# port of the Mozilla Universal Charset Detector 包装成一个非常简单的 API:

var encoding = FileEncoding.DetectFileEncoding(txtFile);

【讨论】:

  • 这应该更高,它提供了一个非常简单的解决方案:让其他人做工作:D
  • 这个库是 GPL
  • 是吗?我看到一个 MIT 许可证,它使用三重许可组件 (UDE),其中一个是 MPL。我一直在尝试确定 UDE 对于专有产品是否存在问题,因此,如果您有更多信息,将不胜感激。
【解决方案7】:

我的解决方案是使用带有一些后备功能的内置内容。

我从 stackoverflow 上另一个类似问题的答案中选择了策略,但现在找不到。

它首先使用StreamReader中的内置逻辑检查BOM,如果有BOM,编码将不是Encoding.Default,我们应该相信这个结果。

如果不是,它检查字节序列是否是有效的 UTF-8 序列。如果是,它将猜测 UTF-8 作为编码,如果不是,则再次使用默认的 ASCII 编码。

static Encoding getEncoding(string path) {
    var stream = new FileStream(path, FileMode.Open);
    var reader = new StreamReader(stream, Encoding.Default, true);
    reader.Read();

    if (reader.CurrentEncoding != Encoding.Default) {
        reader.Close();
        return reader.CurrentEncoding;
    }

    stream.Position = 0;

    reader = new StreamReader(stream, new UTF8Encoding(false, true));
    try {
        reader.ReadToEnd();
        reader.Close();
        return Encoding.UTF8;
    }
    catch (Exception) {
        reader.Close();
        return Encoding.Default;
    }
}

【讨论】:

    【解决方案8】:

    注意:这是一个实验,旨在了解 UTF-8 编码在内部是如何工作的。 The solution offered by vilicvane,使用初始化为在解码失败时抛出异常的UTF8Encoding对象,要简单得多,而且基本上做同样的事情。


    我编写这段代码是为了区分 UTF-8 和 Windows-1252。但是它不应该用于巨大的文本文件,因为它将整个内容加载到内存中并完全扫描它。我将它用于 .srt 字幕文件,只是为了能够将它们保存回加载它们的编码中。

    作为 ref 的函数的编码应该是 8 位后备编码,以防检测到文件不是有效的 UTF-8;通常,在 Windows 系统上,这将是 Windows-1252。这并没有像检查实际有效的 ascii 范围那样做任何花哨的事情,即使在字节顺序标记上也不会检测到 UTF-16。

    按位检测背后的理论可以在这里找到: https://ianthehenry.com/2015/1/17/decoding-utf-8/

    基本上,第一个字节的位范围决定了它后面有多少是 UTF-8 实体的一部分。它后面的这些字节总是在同一个位范围内。

    /// <summary>
    /// Reads a text file, and detects whether its encoding is valid UTF-8 or ascii.
    /// If not, decodes the text using the given fallback encoding.
    /// Bit-wise mechanism for detecting valid UTF-8 based on
    /// https://ianthehenry.com/2015/1/17/decoding-utf-8/
    /// </summary>
    /// <param name="docBytes">The bytes read from the file.</param>
    /// <param name="encoding">The default encoding to use as fallback if the text is detected not to be pure ascii or UTF-8 compliant. This ref parameter is changed to the detected encoding.</param>
    /// <returns>The contents of the read file, as String.</returns>
    public static String ReadFileAndGetEncoding(Byte[] docBytes, ref Encoding encoding)
    {
        if (encoding == null)
            encoding = Encoding.GetEncoding(1252);
        Int32 len = docBytes.Length;
        // byte order mark for utf-8. Easiest way of detecting encoding.
        if (len > 3 && docBytes[0] == 0xEF && docBytes[1] == 0xBB && docBytes[2] == 0xBF)
        {
            encoding = new UTF8Encoding(true);
            // Note that even when initialising an encoding to have
            // a BOM, it does not cut it off the front of the input.
            return encoding.GetString(docBytes, 3, len - 3);
        }
        Boolean isPureAscii = true;
        Boolean isUtf8Valid = true;
        for (Int32 i = 0; i < len; ++i)
        {
            Int32 skip = TestUtf8(docBytes, i);
            if (skip == 0)
                continue;
            if (isPureAscii)
                isPureAscii = false;
            if (skip < 0)
            {
                isUtf8Valid = false;
                // if invalid utf8 is detected, there's no sense in going on.
                break;
            }
            i += skip;
        }
        if (isPureAscii)
            encoding = new ASCIIEncoding(); // pure 7-bit ascii.
        else if (isUtf8Valid)
            encoding = new UTF8Encoding(false);
        // else, retain given encoding. This should be an 8-bit encoding like Windows-1252.
        return encoding.GetString(docBytes);
    }
    
    /// <summary>
    /// Tests if the bytes following the given offset are UTF-8 valid, and
    /// returns the amount of bytes to skip ahead to do the next read if it is.
    /// If the text is not UTF-8 valid it returns -1.
    /// </summary>
    /// <param name="binFile">Byte array to test</param>
    /// <param name="offset">Offset in the byte array to test.</param>
    /// <returns>The amount of bytes to skip ahead for the next read, or -1 if the byte sequence wasn't valid UTF-8</returns>
    public static Int32 TestUtf8(Byte[] binFile, Int32 offset)
    {
        // 7 bytes (so 6 added bytes) is the maximum the UTF-8 design could support,
        // but in reality it only goes up to 3, meaning the full amount is 4.
        const Int32 maxUtf8Length = 4;
        Byte current = binFile[offset];
        if ((current & 0x80) == 0)
            return 0; // valid 7-bit ascii. Added length is 0 bytes.
        Int32 len = binFile.Length;
        for (Int32 addedlength = 1; addedlength < maxUtf8Length; ++addedlength)
        {
            Int32 fullmask = 0x80;
            Int32 testmask = 0;
            // This code adds shifted bits to get the desired full mask.
            // If the full mask is [111]0 0000, then test mask will be [110]0 0000. Since this is
            // effectively always the previous step in the iteration I just store it each time.
            for (Int32 i = 0; i <= addedlength; ++i)
            {
                testmask = fullmask;
                fullmask += (0x80 >> (i+1));
            }
            // figure out bit masks from level
            if ((current & fullmask) == testmask)
            {
                if (offset + addedlength >= len)
                    return -1;
                // Lookahead. Pattern of any following bytes is always 10xxxxxx
                for (Int32 i = 1; i <= addedlength; ++i)
                {
                    if ((binFile[offset + i] & 0xC0) != 0x80)
                        return -1;
                }
                return addedlength;
            }
        }
        // Value is greater than the maximum allowed for utf8. Deemed invalid.
        return -1;
    }
    

    【讨论】:

    • if ((current &amp; 0xE0) == 0xC0) { ... } else if ((current &amp; 0xF0) == 0xE0) { ... } else if ((current &amp; 0xF0) == 0xE0) { ... } else if ((current &amp; 0xF8) == 0xF0) { ... } 之后也没有最后一个else 语句。我想else case 是无效的 utf8:isUtf8Valid = false;。你愿意吗?
    • @hal 啊,真的......我用更通用(和更高级)的系统更新了我自己的代码,该系统使用高达 3 的循环,但在技术上可以更改为进一步循环(规范对此有点不清楚;我认为可以将 UTF-8 扩展到最多 6 个添加字节,但在当前实现中只使用了 3 个字节),所以我没有更新此代码。
    • @hal 将其更新为我的新解决方案。原理保持不变,但位掩码是在循环中创建和检查的,而不是全部在代码中显式写出。
    【解决方案9】:

    我最后的工作方法是通过检测编码从字节数组创建的字符串中的无效字符来尝试预期编码的潜在候选者。 如果我没有遇到无效字符,我想测试的编码对于测试的数据可以正常工作。

    对我来说,只考虑拉丁语和德语特殊字符,为了确定字节数组的正确编码,我尝试使用这种方法检测字符串中的无效字符:

        /// <summary>
        /// detect invalid characters in string, use to detect improper encoding
        /// </summary>
        /// <param name="s"></param>
        /// <returns></returns>
        public static bool DetectInvalidChars(string s)
        {
            const string specialChars = "\r\n\t .,;:-_!\"'?()[]{}&%$§=*+~#@|<>äöüÄÖÜß/\\^€";
            return s.Any(ch => !(
                specialChars.Contains(ch) ||
                (ch >= '0' && ch <= '9') ||
                (ch >= 'a' && ch <= 'z') ||
                (ch >= 'A' && ch <= 'Z')));
        }
    

    (注意:如果您要考虑其他基于拉丁语的语言,您可能需要修改代码中的 specialChars const 字符串)

    然后我就这样使用(我只希望 UTF-8 或默认编码):

            // determine encoding by detecting invalid characters in string
            var invoiceXmlText = Encoding.UTF8.GetString(invoiceXmlBytes); // try utf-8 first
            if (StringFuncs.DetectInvalidChars(invoiceXmlText))
                invoiceXmlText = Encoding.Default.GetString(invoiceXmlBytes); // fallback to default
    

    【讨论】:

      【解决方案10】:

      我在 GitHub 上找到了新库:CharsetDetector/UTF-unknown

      在 C# 中构建的字符集检测器 - .NET Core 2-3、.NET 标准 1-2 和 .NET 4+

      它也是Mozilla Universal Charset Detector基于其他存储库的一个端口。

      CharsetDetector/UTF-unknown 有一个名为 CharsetDetector 的类。

      CharsetDetector 包含一些静态编码检测方法:

      • CharsetDetector.DetectFromFile()
      • CharsetDetector.DetectFromStream()
      • CharsetDetector.DetectFromBytes()

      检测到的结果在类 DetectionResult 中具有属性 Detected,它是类 DetectionDetail 的实例,具有以下属性:

      • EncodingName
      • Encoding
      • Confidence

      下面是一个展示用法的例子:

      // Program.cs
      using System;
      using System.Text;
      using UtfUnknown;
      
      namespace ConsoleExample
      {
          public class Program
          {
              public static void Main(string[] args)
              {
                  string filename = @"E:\new-file.txt";
                  DetectDemo(filename);
              }
      
              /// <summary>
              /// Command line example: detect the encoding of the given file.
              /// </summary>
              /// <param name="filename">a filename</param>
              public static void DetectDemo(string filename)
              {
                  // Detect from File
                  DetectionResult result = CharsetDetector.DetectFromFile(filename);
                  // Get the best Detection
                  DetectionDetail resultDetected = result.Detected;
      
                  // detected result may be null.
                  if (resultDetected != null)
                  {
                      // Get the alias of the found encoding
                      string encodingName = resultDetected.EncodingName;
                      // Get the System.Text.Encoding of the found encoding (can be null if not available)
                      Encoding encoding = resultDetected.Encoding;
                      // Get the confidence of the found encoding (between 0 and 1)
                      float confidence = resultDetected.Confidence;
      
                      if (encoding != null)
                      {
                          Console.WriteLine($"Detection completed: {filename}");
                          Console.WriteLine($"EncodingWebName: {encoding.WebName}{Environment.NewLine}Confidence: {confidence}");
                      }
                      else
                      {
                          Console.WriteLine($"Detection completed: {filename}");
                          Console.WriteLine($"(Encoding is null){Environment.NewLine}EncodingName: {encodingName}{Environment.NewLine}Confidence: {confidence}");
                      }
                  }
                  else
                  {
                      Console.WriteLine($"Detection failed: {filename}");
                  }
              }
          }
      }
      

      示例结果截图:

      【讨论】:

      • UTF-unknown 对我不起作用;许多错误的结果。
      【解决方案11】:

      正如其他人所提到的,C# 中的string总是编码为 UTF-16LE (System.Text.Encoding.Unicode)。

      字里行间,我相信您真正关心的是string 中的字符是否与其他一些已知 编码兼容 (即它们会“适合”其他代码页吗?)。

      在这种情况下,我找到的最正确的解决方案是尝试转换并查看字符串是否更改。如果string 中的字符不“适合”目标编码,编码器会将其替换为某些标记字符(例如,'?' 很常见)。

      
          // using System.Text;
      
          // And if you're using the "System.Text.Encoding.CodePages" NuGet package, you 
          // need to call this once or GetEncoding will raise a NotSupportedException:
          // Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);
      
          var srcEnc = Encoding.Unicode;
          var dstEnc = Encoding.GetEncoding(1252); // 1252 Requires use of the "System.Text.Encoding.CodePages" NuGet package.
          string srcText = "Some text you want to check";
          string dstText = dstEnc.GetString(Encoding.Convert(srcEnc, dstEnc, srcEnc.GetBytes(srcText)));
      
          // if (srcText == dstText) the srcText "fits" (it's compatible).
          // else the srcText doesn't "fit" (it's not compatible)
      
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2013-04-04
        • 2013-10-31
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-07-07
        相关资源
        最近更新 更多