我有一个 ANSI 编码的文件,我想将从文件中读取的行转换为 ASCII。
我该如何在 C# 中执行此操作?
编辑:如果我使用“BinaryReader”
BinaryReader reader = new BinaryReader(input, Encoding.Default);
但是这个阅读器需要(Stream,Encoding)但“Stream”是一个抽象怎么办!我应该把他将从中读取的文件的路径放在哪里?
我有一个 ANSI 编码的文件,我想将从文件中读取的行转换为 ASCII。
我该如何在 C# 中执行此操作?
编辑:如果我使用“BinaryReader”
BinaryReader reader = new BinaryReader(input, Encoding.Default);
但是这个阅读器需要(Stream,Encoding)但“Stream”是一个抽象怎么办!我应该把他将从中读取的文件的路径放在哪里?
从 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,但这并没有什么意义,因为:
更新:
针对更新后的问题,您可以BinaryReader
这样使用:
BinaryReader reader = new BinaryReader(File.Open("foo.txt", FileMode.Open),
Encoding.GetEncoding(1252));
基本上,您需要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
。