gpt4 book ai didi

c# - 数据库中存储的字符串的编码问题

转载 作者:太空宇宙 更新时间:2023-11-03 20:01:06 25 4
gpt4 key购买 nike

我有一个编码问题。我的 MongoDB 中有编码错误的文本。我的数据库中文本的源文件是用 ISO-8859-1 编码的。现在,在我的数据库中查看它时,一些字符被破坏了(变成“�”)。

目前,在从数据库中检索文本时,我尝试了以下代码。

var t = Collection.FindOne(Query.EQ("id", "2014121500892"));
string message = t["b203"].AsString;
Console.WriteLine(ChangeEncoding(message));

第一次尝试:

static string ChangeEncoding(string message)
{

System.Text.Encoding srcEnc = System.Text.Encoding.GetEncoding("ISO-8859-1");
System.Text.Encoding destEnc = System.Text.Encoding.GetEncoding("UTF-8");
byte[] bData = srcEnc.GetBytes(message);
byte[] bResult = System.Text.Encoding.Convert(srcEnc, destEnc, bData);
return destEnc.GetString(bResult);
}

第二次尝试:

static string ChangeEncoding(string message)
{
File.WriteAllText("text.txt", message, Encoding.GetEncoding("ISO-8859-1"));
return File.ReadAllText("text.txt");
}

数据库中的示例文本:

Box aus Pappe f�r A8-Lernk�rtchen

期望的结果:

我希望能够在控制台中将其打印为:

Box aus Pappe für A8-Lernkärtchen

最佳答案

精简版

您的数据丢失了,没有通用的解决方案来恢复原始字符串。

更长的版本

存储数据时应该发生了什么,字符串编码为 ISO-8859-1 但存储为 Unicode UTF8。这是一个例子:

string orig = "Lernkärtchen";
byte[] iso88891Bytes = Encoding.GetEncoding("ISO-8859-1").GetBytes(orig);
// { 76, 101, 114, 110, 107, 228, 114, 116, 99, 104, 101, 110 }
// 'L', 'e', 'r', 'n', 'k', 'ä', 'r', 't', 'c', 'h', 'e', 'n'

当此数据(以某种方式...)传递到仅适用于 Unicode 字符串的数据库时:

string storedValue = Encoding.UTF8.GetString(iso88891Bytes);
byte[] dbData = Encoding.UTF8.GetBytes(storedValue);
// { 76, 101, 114, 110, 107, 239, 191, 189, 114, 116, 99, 104, 101, 110 }
// 'L', 'e', 'r', 'n', 'k', '�', 'r', 't', 'c', 'h', 'e', 'n'

问题是字节 228(11100100 二进制)对 utf8 无效,因为对于这样的字节,必须跟在其他 2 个字节之后,其值 > 127。有关详细信息,请参阅 UTF8 on Wikipedia , “描述”一章。

因此,以前称为字符“ä”的字节无法解码为有效的 Unicode 字符,并被字节 239、191 和 189 替换。即 11101111、10111111 和 10111101,这导致了代码指向值为 1111111111111101 (0xFFFD) 的点,这是您在输出中看到的字符“�”。

此字符正是用于此目的。在 Wikipedia Unicode special characters page它说:

U+FFFD � replacement character used to replace an unknown or unrepresentable character

尝试还原该更改?祝你好运。

顺便说一句,Unicode 和 UTF-8 很棒 ♥,不要使用其他任何东西 ☠!

关于c# - 数据库中存储的字符串的编码问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28216928/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com