如何阅读ANSI编码和非英文字母的文本文件?

Mic*_*elT 41 .net c# unicode utf-8 character-encoding

我有一个包含非英语字符的文件,并使用非英语代码页以ANSI编码保存.如何在C#中读取此文件并正确查看文件内容?

不工作

StreamReader sr=new StreamReader(@"C:\APPLICATIONS.xml",Encoding.ASCII);
var ags = sr.ReadToEnd();
sr=new StreamReader(@"C:\APPLICATIONS.xml",Encoding.UTF8);
ags = sr.ReadToEnd();
sr=new StreamReader(@"C:\APPLICATIONS.xml",Encoding.Unicode);
ags = sr.ReadToEnd();
Run Code Online (Sandbox Code Playgroud)

工作但我需要提前知道代码页是什么,这是不可能的.

sr=new StreamReader(@"C:\APPLICATIONS.xml",Encoding.GetEncoding(1252));
ags = sr.ReadToEnd();
Run Code Online (Sandbox Code Playgroud)

L.B*_*L.B 63

 var text = File.ReadAllText(file, Encoding.GetEncoding(codePage));
Run Code Online (Sandbox Code Playgroud)

代码页列表:http://msdn.microsoft.com/en-us/library/windows/desktop/dd317756(v = vs.85).aspx

  • @MichaelT [如何检测文本文件的编码/代码页](http://stackoverflow.com/questions/90838/how-can-i-detect-the-encoding-codepage-of-a-text-file ) (5认同)
  • 请记住http://www.joelonsoftware.com/articles/Unicode.html - 绝对最低每个软件开发人员绝对必须知道关于Unicode和字符集(没有任何借口!)作者:Joel Spolsky (5认同)
  • 我需要知道代码页。我事先并不知道。 (2认同)

小智 6

当您的文本文件使用高ANSI编码时,您会得到问号菱形字符-这意味着它使用127至255之间的字符。这些字符设置了第八个(即最高有效)位。当ASP.NET读取文本文件时,它将采用UTF-8编码,并且最高有效位具有特殊含义。

您必须通过告诉ASP.NET代码页为1252,来强制将文本文件解释为高ANSI编码:

String textFilePhysicalPath = System.Web.HttpContext.Current.Server.MapPath("~/textfiles/MyInputFile.txt");
String contents = File.ReadAllText(textFilePhysicalPath, System.Text.Encoding.GetEncoding(1252));
lblContents.Text = contents.Replace("\n", "<br />");  // change linebreaks to HTML
Run Code Online (Sandbox Code Playgroud)

  • 恕我直言,应该是接受的答案。此外,使用 .NET core 2.x 或 .NET Standard,您将遇到一个新问题。代码页需要在 &lt;sigh&gt; 之前注册。请参阅 /sf/ask/2650905911/ (2认同)
  • 请注意,.NET Core 仅支持 ASCII、ISO-8859-1 和 Unicode 编码。因此,当尝试使用编码 1252(ANSI Latin 1;西欧 Windows)时,您将收到错误。对我有用的是编码 65000 (utf-7 Unicode)。 (2认同)