通过C#读取txt文件(使用unicode和utf8) [英] Read txt files (in unicode and utf8) by means of C#

查看:54
本文介绍了通过C#读取txt文件(使用unicode和utf8)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我创建了两个具有相同内容谢谢-спасибо"的txt文件(Windows记事本),并将它们保存在utf8和unicode中.在记事本中,它们看起来不错.然后我尝试使用.Net来阅读它们:

I created two txt files (windows notepad) with the same content "thank you - спасибо" and saved them in utf8 and unicode. In notepad they look fine. Then I tried to read them using .Net:

...File.ReadAllText(utf8FileFullName, Encoding.UTF8);

...File.ReadAllText(unicodeFileFullName, Encoding.Unicode);

但是在两种情况下,我都得到了谢谢-???????".怎么了?

But in both cases I got this "thank you - ???????". What's wrong?

已更新: utf8的代码

Upd: code for utf8

static void Main(string[] args)
        {
            var encoding = Encoding.UTF8;
            var file = new FileInfo(@"D:\encodes\enc.txt");
            Console.OutputEncoding = encoding;
            var content = File.ReadAllText(file.FullName, encoding);
            Console.WriteLine("encoding: " + encoding);
            Console.WriteLine("content: " + content);
            Console.ReadLine();
        }

结果: 感谢ÑпаÑиÐбо

推荐答案

编辑为UTF8的字符应支持.似乎您正在输出到未设置其编码的控制台或位置.如果是这样,则需要设置编码.对于控制台,您可以执行此操作

Edited as UTF8 should support the characters. It seems that you're outputting to a console or a location which hasn't had its encoding set. If so, you need to set the encoding. For the console you can do this

string allText = File.ReadAllText(unicodeFileFullName, Encoding.UTF8);
Console.OutputEncoding = Encoding.UTF8;
Console.WriteLine(allText);

这篇关于通过C#读取txt文件(使用unicode和utf8)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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