我想将字符串变量从UTF8转换为ISO-8859-1,因为对于ä,ö,ü这样的特殊字符,我在C#中看到?
。为了实现这个目标,我找到了这个post。但这对我不起作用。我试图找出原因。...
我已经用以下代码在C#中观察到原始字符串和转换后的字符串的字节:
System.IO.MemoryStream stream = new System.IO.MemoryStream();
System.Runtime.Serialization.IFormatter formatter = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
formatter.Serialize(stream, dt2.Rows[0][0]); // I read my string from a datatable and it is utf8 encoded
byte[] bytes = stream.GetBuffer();
这行代码:
Console.WriteLine(BitConverter.ToString(bytes).Replace("-", ""));
返回:
4652495343484BEFBFBD53455A55424552454954554E47454E2020
现在,我想编码为ISO-8859-1。为此,我使用以下代码:
var srcEncoding = Encoding.Default; // The original bytes are utf8 hence here "Default"
var destEncoding = Encoding.GetEncoding("ISO-8859-1");
var destBytes = Encoding.Convert(srcEncoding, destEncoding, bytes);
然后运行代码行:
Console.WriteLine(BitConverter.ToString(destBytes).Replace("-", ""));
我得到相同的十六进制代码。转换似乎无法正常工作
4652495343484BEFBFBD53455A55424552454954554E47454E2020
您知道为什么转换对我不起作用吗?
答案 0 :(得分:2)
答案 1 :(得分:0)
没有理由惹恼MemoryStream
和BinaryFormatter
。只需使用适当的GetString
的方法GetBytes
和Encoding
。
byte[] oldBytes = new byte[] { 0x46, 0x52, 0x49, 0x53, 0x43, 0x48,
0x4B, 0xEF, 0xBF, 0xBD, 0x53, 0x45, 0x5A, 0x55, 0x42, 0x45, 0x52,
0x45, 0x49, 0x54, 0x55, 0x4E, 0x47, 0x45, 0x4E, 0x20, 0x20 };
Console.WriteLine($"oldBytes: {BitConverter.ToString(oldBytes)} ({oldBytes.Length})");
string oldStr = Encoding.UTF8.GetString(oldBytes);
Console.WriteLine($"oldStr: <{oldStr}>");
byte[] newBytes = Encoding.GetEncoding("ISO-8859-1").GetBytes(oldStr);
Console.WriteLine($"newBytes: {BitConverter.ToString(newBytes)} ({newBytes.Length})");
string newStr = Encoding.GetEncoding("ISO-8859-1").GetString(newBytes);
Console.WriteLine($"newStr: <{newStr}>");
输出:
oldBytes: 46-52-49-53-43-48-4B-EF-BF-BD-53-45-5A-55-42-45-52-45-49-54-55-4E-47-45-4E-20-20 (27)
oldStr: <FRISCHK�SEZUBEREITUNGEN >
newBytes: 46-52-49-53-43-48-4B-3F-53-45-5A-55-42-45-52-45-49-54-55-4E-47-45-4E-20-20 (25)
newStr: <FRISCHK?SEZUBEREITUNGEN >