19

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

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


编辑:如果我使用“BinaryReader” BinaryReader reader = new BinaryReader(input, Encoding.Default); 但是这个阅读器需要(Stream,Encoding)但“Stream”是一个抽象怎么办!我应该把他将从中读取的文件的路径放在哪里?

4

2 回答 2

30

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

不过,您可以尝试使用 UTF-8 转换为 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);

当然你可以用 ASCII 替换 UTF8,但这并没有什么意义,因为:

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

更新:

针对更新后的问题,您可以BinaryReader这样使用:

BinaryReader reader = new BinaryReader(File.Open("foo.txt", FileMode.Open),
                                       Encoding.GetEncoding(1252));
于 2009-04-09T11:55:53.347 回答
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);

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

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

于 2009-04-09T11:56:25.093 回答