我有一个编码问题。我的MongoDB中的文本编码错误。我的数据库中文本的源文件是按照ISO-8859-1编码的。现在,在我的数据库中查看它时,一些字符被破坏了(变成了``...'')。
目前,在从db检索文本时,我尝试了以下代码。
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");
}
db中的示例文本:
A8学习卡的纸板箱
我希望能够在控制台中将其打印为:
A8学习卡的纸板箱
您的数据丢失,并且没有通用的解决方案来恢复原始字符串。
数据存储时所发生的情况是,字符串编码为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无效,因为对于这样的字节,必须跟随其他两个字节,其值>127。有关详细信息,请参阅Wikipedia上的UTF8,“说明”一章。
因此,发生的事情是以前称为字符'ä'的字节无法解码为有效的unicode字符,并被字节239、191和189代替。这是11101111、10111111和10111101,这会导致代码点具有值1111111111111101(0xFFFD)这是您在输出中看到的字符'。
该字符正是用于此目的。在Wikipedia Unicode特殊字符页面上,它显示:
U + FFFD-替换字符,用于替换未知或无法表示的字符
尝试还原该更改?祝你好运。
顺便说一句,Unicode和UTF-8很棒♥,切勿使用其他任何东西☠!
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句