2

I have an asp.net GET webservice that takes in a URL parameter, runs some logic, and then passes back a þ delimited list of values.

The problem I have is the service making the request is using Windows-1252 encoding, so the þ character doesn't display properly when it's returned to the requesting machine. I'm looking for a quick way to convert a string from UTF8 to Windows-1252 to pass back.

John Saunders
  • 160,644
  • 26
  • 247
  • 397
user3486740
  • 79
  • 1
  • 1
  • 7
  • 2
    If you've already got a *string*, there's no encoding involved... or rather, it's already been applied. You should be applying an encoding to a `byte[]` to get a string, and then back again. (Or use `Encoding.Convert` to do this in one go.) It doesn't help that you haven't shown us *any* code... – Jon Skeet Oct 29 '14 at 17:56

2 Answers2

2

Convert your string inputStr to byte array :

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

Convert it to 1252:

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

Get the string back:

w1252.GetString(output);
e4rthdog
  • 5,103
  • 4
  • 40
  • 89
0

As Jon Skeet already pointed out, the string itself has no encoding, it's the byte[] that has an encoding. So you need to know which encoding has been applied to your string, based on this you can retrieve the byte[] for the string and convert it to the desired encoding. The resulting byte[] can then be further processed (e.g. written to a file, returned in a 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
Robar
  • 1,929
  • 2
  • 30
  • 61