使用C#将文本文件从ANSI转换为ASCII

BDe*_*per 19 c# encoding ascii character-encoding

我有一个ANSI编码的文件,我想将我从文件中读取的行转换为ASCII.

我如何在C#中执行此操作?


编辑:如果我使用"BinaryReader", BinaryReader reader = new BinaryReader(input, Encoding.Default); 但这个读取器(流,编码),但"流"是一个抽象!我应该在哪里放置他将从中读取的文件的路径?

Can*_*der 30

从ANSI到ASCII的直接转换可能并非总是可行,因为ANSI是ASCII的超集.

您可以尝试使用转换为UTF-8 Encoding,但:

Encoding ANSI = Encoding.GetEncoding(1252);

byte[] ansiBytes = ANSI.GetBytes(str);
byte[] utf8Bytes = Encoding.Convert(ANSI, Encoding.UTF8, ansiBytes);

String utf8String = Encoding.UTF8.GetString(utf8Bytes);
Run Code Online (Sandbox Code Playgroud)

当然你可以用ASCII代替UTF8,但是这没有用,因为:

  • 如果原始字符串不包含任何字节> 126,那么它已经是ASCII
  • 如果原始字符串确实包含一个或多个字节> 126,那么这些字节将丢失

更新:

为了回应更新的问题,您可以BinaryReader像这样使用:

BinaryReader reader = new BinaryReader(File.Open("foo.txt", FileMode.Open),
                                       Encoding.GetEncoding(1252));
Run Code Online (Sandbox Code Playgroud)


Mar*_*ell 23

基本上,您需要Encoding在读/写文件时指定.例如:

// read with the **local** system default ANSI page
string text = File.ReadAllText(path, Encoding.Default); 

// ** I'm not sure you need to do this next bit - it sounds like
//  you just want to read it? **

// write as ASCII (if you want to do this)
File.WriteAllText(path2, text, Encoding.ASCII);
Run Code Online (Sandbox Code Playgroud)

请注意,一旦您阅读它,text在内存中实际上是unicode.

您可以使用选择不同的代码页Encoding.GetEncoding.