将问题 ANSI 转换为 UTF8 C# [英] Converting problem ANSI to UTF8 C#

查看:41
本文介绍了将问题 ANSI 转换为 UTF8 C#的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 c# 中将文本文件从 ANSI 转换为 UTF8 时遇到问题.我尝试在浏览器中显示结果.

I have a problem with converting a text file from ANSI to UTF8 in c#. I try to display the results in a browser.

所以我有一个包含许多重音字符的文本文件.它以 ANSI 编码,因此我必须将其转换为 utf8,因为在浏览器中而不是出现?"的重音字符.无论我如何尝试转换为 UTF8,它仍然是一个?".但是,如果我将 notepad++ 中的文本文件转换为 utf8,那么重音字符就会显示得很好.

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?

是的,你来晚了.从文件中读取字符串时需要指定 ANSI.在内存中,它始终是 Unicode (UTF16).

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屋!

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