从 UTF8 转换为 ISO-8859-1 不起作用

Converting from UTF8 to ISO-8859-1 doesn't work

我想将字符串变量从 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("-", ""));

returns:

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

你知道为什么转换对我不起作用吗?

您的字符串不包含 a-umlaut。

它包含"Unicode replacement character"

在您获得 byte[] bytes 之前发生的任何转换都已经失去了您的 a-umlaut。

没有理由搞乱 MemoryStreamBinaryFormatter。只需使用适当的 Encoding.

的方法 GetStringGetBytes
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  >