转换问题ANSI为UTF8 C# [英] Converting problem ANSI to UTF8 C#
问题描述
我在C#中从ANSI转换文本文件为UTF8的一个问题。我尝试显示在浏览器中的效果。
所以,我在这许多重音字符这个文本文件。它在ANSI编码,所以我必须把它转换为UTF8,因为在浏览器中,而不是出现在accentchars?。不管我怎么想转换为UTF8它仍然是一个?。但如果我转换成文本文件在记事本++为UTF8那么重音字符都desplayed好
这里是编码代码和平,我提出:
公共字符串编码(字符串文本)
{
//编码字符串作为ASCII字节数组
字节[] = myASCIIBytes ASCIIEncoding.ASCII.GetBytes(文本);
//的ASCII字节数组转换为UTF-8字节数组
字节[] = myUTF8Bytes ASCIIEncoding.Convert(ASCIIEncoding.ASCII,UTF8Encoding.UTF8,myASCIIBytes);
//重组从UTF-8字节数组
返回UTF8Encoding.UTF8.GetString(myUTF8Bytes)的字符串;
}
你有任何想法,为什么会出现这种情况?
你有任何想法,为什么会出现这种情况?
块引用>
是的,你来得太晚了。您需要在读取文件中的字符串来指定ANSI。在内存方面它总是个Unicode(UTF16)。
I have a problem with converting a text file from ANSI to UTF8 in c#. I try to display the results in a browser.
So I have a this text file with many accent character in it. Its encoded in ANSI, so I have to convert it to utf8 because in the browser instead of the accentchars appearing "?". No matter how I tried to convert to UTF8 it was still a "?". But if I convert the text file in notepad++ to utf8 then the accent chars are desplayed good.
here is a peace of encoding code that I made:
public string Encode(string text) { // encode the string as an ASCII byte array byte[] myASCIIBytes = ASCIIEncoding.ASCII.GetBytes(text); // convert the ASCII byte array to a UTF-8 byte array byte[] myUTF8Bytes = ASCIIEncoding.Convert(ASCIIEncoding.ASCII, UTF8Encoding.UTF8, myASCIIBytes); // reconstitute a string from the UTF-8 byte array return UTF8Encoding.UTF8.GetString(myUTF8Bytes); }
Do you have any idea why is this happening?
解决方案Do you have any idea why is this happening?
Yes, you're too late. You need to specify ANSI when you read the string from file. In memory it's always Unicode (UTF16).
这篇关于转换问题ANSI为UTF8 C#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!