我如何在C#中的字符串转换为UTF-8? [英] How can I transform string to UTF-8 in C#?

查看:270
本文介绍了我如何在C#中的字符串转换为UTF-8?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有我从第三方应用程序收到一个字符串,我想用C#在我的Windows表面的任何语言​​正确显示。

I have a string that I receive from a third party app and I would like to display it correctly in any language using C# on my Windows Surface.

由于不正确的编码,我的一块字符串看起来像这样在西班牙语:

Due to incorrect encoding, a piece of my string looks like this in Spanish:

Acción

而它看起来应该是这样的:

whereas it should look like this:

行动组织

据对这个问题的答案:
   <一href=\"http://stackoverflow.com/questions/13993135/how-to-know-string-encoding-in-c-sharp/13994368#13994368\">How要知道在C#字符串编码,我收到的编码应在UTF-8来了,但它是阅读Encoding.Default(可能ANSI?)。

According to the answer on this question: How to know string encoding in C#, the encoding I am receiving should be coming on UTF-8 already, but it is read on Encoding.Default (probably ANSI?).

我想这个字符串转换成真正的UTF-8,但其中一个问题是,我只能看到Encoding类的一个子集(UTF8和统一code仅属性),可能是因为我限于窗户表面API。

I am trying to transform this string into real UTF-8, but one of the problems is that I can only see a subset of the Encoding class (UTF8 and Unicode properties only), probably because I'm limited to the windows surface API.

我尝试过的一些片段,我在互联网上找到,但他们都没有被证明是成功至今为东方语言(即韩国)。一个例子是如下:

I have tried some snippets I've found on the internet, but none of them have proved successful so far for eastern languages (i.e. korean). One example is as follows:

var utf8 = Encoding.UTF8;
byte[] utfBytes = utf8.GetBytes(myString);
myString= utf8.GetString(utfBytes, 0, utfBytes.Length);     

我也试过提取字符串转换成字节数组,然后使用UTF8.GetString:

I also tried extracting the string into a byte array and then using UTF8.GetString:

byte[] myByteArray = new byte[myString.Length];
for (int ix = 0; ix < myString.Length; ++ix)
{
    char ch = myString[ix];
    myByteArray[ix] = (byte) ch;
}

myString = Encoding.UTF8.GetString(myByteArray, 0, myString.Length);

你们是否有任何其他想法,我能试试吗?

Do you guys have any other ideas that I could try?

推荐答案

正如你所知道的字符串来作为 Encoding.Default 您可以简单地使用:

As you know the string is coming in as Encoding.Default you could simply use:

byte[] bytes = Encoding.Default.GetBytes(myString);
myString = Encoding.UTF8.GetString(bytes);

这篇关于我如何在C#中的字符串转换为UTF-8?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆