2014-10-29 181 views
0

我有一个asp.net GET webservice,它接受一个URL参数,运行一些逻辑,然后返回一个分隔的值列表。将UTF8转换为Windows-1252

我遇到的问题是使请求的服务使用Windows-1252编码,因此当返回到请求机器时,þ字符无法正确显示。我正在寻找一种快速的方式将字符串从UTF8转换为Windows-1252以传回。

+2

如果你已经有一个*字符串*,没有涉及编码...或者说,它已经被应用。您应该将编码应用于'byte []'来获取字符串,然后再返回。 (或者使用'Encoding.Convert'一次完成此操作。)这并没有帮助你没有向我们显示*任何*代码... – 2014-10-29 17:56:39

回答

1

转换您的字符串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); 
+0

这需要更新。 – Sedrick 2017-07-18 18:36:11

0

由于乔恩斯基特已经指出,字符串本身没有编码,它是编码的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