gpt4 book ai didi

c# - 如何正确地将 iso-8859-1 转换为 utf8?

转载 作者:行者123 更新时间:2023-11-30 15:40:12 25 4
gpt4 key购买 nike

我需要将响应流写入文件。该流包含一个编码页面 (iso-8859-1)。

这是我的代码:

...

using (TextWriter writer = new StreamWriter(tmpFilePath))
{
using (TextReader reader = new StreamReader(answer, Encoding.GetEncoding("ISO-8859-1")))
{

string line = "";
while ((line = reader.ReadLine()) != null)
{

// try to decode
string decoded_line = decode(line);

writer.WriteLine(decoded_line);
}

}

}

...


string decode(string message)
{
string result = "";

Encoding iso = Encoding.GetEncoding("iso-8859-1");
Encoding utf8 = Encoding.UTF8;

byte[] isoBytes = iso.GetBytes(message);
byte[] utf8Bytes = Encoding.Convert(iso, utf8, isoBytes);

result = utf8.GetString(utf8Bytes);

return result;
}

问题是 decode() 不工作

enter image description here

如何正确地将 iso-8859-1 转换为 utf8?

更新

我依靠 fiddler 来获取内容类型:

enter image description here

最佳答案

鉴于这种情况,应该足以:

using (TextWriter writer = new StreamWriter(tmpFilePath, Ecoding.UTF8))
{
using (TextReader reader = new StreamReader(answer, Encoding.GetEncoding("ISO-8859-1")))
{
while ((line = reader.ReadLine()) != null)
{
writer.WriteLine(decoded_line);
}
}
}

如果这不起作用,请检查您的数据。 (第一)行在调试器中看起来如何?

关于c# - 如何正确地将 iso-8859-1 转换为 utf8?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9540936/

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