我有一个asp.net的GET webservice,它接受一个URL参数,运行一些逻辑,然后返回一个用þ分隔的值列表。
问题在于发起请求的服务使用的是Windows-1252编码,所以当返回给请求机器时,þ字符显示不正确。我正在寻找一种快速将字符串从UTF8转换为Windows-1252以便传回的方法。
将字符串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);
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
byte[]
应用编码来获取一个字符串,然后再转回去。(或者使用Encoding.Convert
一次完成这个过程。)你没有展示任何代码也没有帮助。 - undefined