在C#中读取特定编码类型的.txt文件

时间:2011-07-15 06:24:04

标签: c# encoding readfile

  

可能重复:
  How can I detect the encoding/codepage of a text file

我必须读取(文本).txt文件。但我不知道它的编码类型。编码类型可能是

Encoding.ANSI 

Encoding.Unicode

所以我的问题是'我们如何知道并读取特定文件的特定编码类型?'

2 个答案:

答案 0 :(得分:2)

试试这个

StreamReader sr = new StreamReader(@"C:\CreateAsciiFile.txt",true);
string LineText= sr.ReadLine();
System.Text.Encoding enc = sr.CurrentEncoding;

检查此答案可能会对您有所帮助:http://www.eggheadcafe.com/community/aspnet/2/10077748/get-file-encoding.aspx

还要考虑这个问题:Encoding Methods

答案 1 :(得分:1)

一般情况下 - 你不能。 StreamReader构造函数有一个内置的启发式算法,如果你不提供它就可以猜测编码,这对你来说可能已经足够了,但这不是100%的解决方案

阅读Joel Spolsky的这篇文章

http://www.joelonsoftware.com/articles/Unicode.html

获得更多见解。

相关问题