将UTF8转换为Windows-1252

4

我有一个asp.net的GET webservice,它接受一个URL参数,运行一些逻辑,然后返回一个用þ分隔的值列表。

问题在于发起请求的服务使用的是Windows-1252编码,所以当返回给请求机器时,þ字符显示不正确。我正在寻找一种快速将字符串从UTF8转换为Windows-1252以便传回的方法。


2
如果你已经有一个字符串,那么就不涉及编码...或者说,它已经被应用了。你应该对byte[]应用编码来获取一个字符串,然后再转回去。(或者使用Encoding.Convert一次完成这个过程。)你没有展示任何代码也没有帮助。 - undefined
2个回答

2

将字符串inputStr转换为字节数组:

byte[] bytes = new byte[inputStr.Length * sizeof(char)];
System.Buffer.BlockCopy(inputStr.ToCharArray(), 0, bytes, 0, bytes.Length);

将其转换为1252:

Encoding w1252 = Encoding.GetEncoding(1252);
byte[] output = Encoding.Convert(utf8, w1252, inputStr);

获取字符串:
w1252.GetString(output);

这需要更新。 - undefined

0
如Jon Skeet所指出的那样,字符串本身没有编码,而是byte[]具有编码。因此,您需要知道应用于字符串的编码,根据这个编码,您可以检索字符串的byte[]并将其转换为所需的编码。然后,可以进一步处理生成的byte[](例如写入文件,返回到HttpRequest等)。
// get the correct encodings 
var srcEncoding = Encoding.UTF8; // utf-8
var destEncoding = Encoding.GetEncoding(1252); // windows-1252

// convert the source bytes to the destination bytes
var destBytes = Encoding.Convert(srcEncoding, destEncoding, srcEncoding.GetBytes(srcString));

// process the byte[]
File.WriteAllBytes("myFile", destBytes); // write it to a file OR ...
var destString = destEncoding.GetString(destBytes); // ... get the string

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接