开发者

Convert UTF-16 text to another encoding (Windows-1250)

I have a text in a variable, text, encoded in the default (UTF-16) encoding. I would like to change it to Windows-1250. I have:

pub开发者_运维百科lic static string EncodeToWin1250(string text)
{
    Encoding unicode = Encoding.Unicode;
    Encoding win1250 = Encoding.GetEncoding(1250);

    byte[] unicodeBytes = unicode.GetBytes(text);
    byte[] win1250Bytes = Encoding.Convert(unicode, win1250, unicodeBytes);

    char[] win1250Chars = new char[win1250.GetCharCount(win1250Bytes, 0, win1250Bytes.Length)];
    win1250.GetChars(win1250Bytes, 0, win1250Bytes.Length, win1250Chars, 0);
    text = new string(win1250Chars);
    return text;
}

but so far it doesn't work.

How do I fix this problem?

I am returning the string as a file:

[...]
result = BLL.DataExchange.MoneyS3.MoneyS3Export.EncodeToWin1250(result);
Context.Response.Clear();
Context.Response.AddHeader("Content-Disposition", "attachment; filename=invoicesIssued.xml");
Context.Response.ContentType = "application/octet-stream";
Context.Response.BufferOutput = false;
Context.Response.Write(result);
Context.Response.Flush();
Context.Response.Close();


All strings are stored internally as Unicode in .NET.

You can convert a string to a byte stream using a codepage, as your code does. But your can't change the internal representation of the string: It's Unicode (encoded as UTF16), period.

You may dump your encoded byte stream to a file or wherever you want. But you can't change the internal encoding of .NET string objects.

Your function should return a byte[] instead of a string (win1250Chars actually)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜