我有一个ANSI编码的文件,我想将从文件读取的行转换为ASCII。使用C#将ANSI文本文件转换为ASCII码
如何在C#中执行此操作?
编辑:如果我使用 “BinaryReader在” BinaryReader reader = new BinaryReader(input, Encoding.Default);
但读者需要(流,编码) 但 “流” 是一个抽象的!我应该在哪里放置他将读取的文件的路径?
我有一个ANSI编码的文件,我想将从文件读取的行转换为ASCII。使用C#将ANSI文本文件转换为ASCII码
如何在C#中执行此操作?
编辑:如果我使用 “BinaryReader在” BinaryReader reader = new BinaryReader(input, Encoding.Default);
但读者需要(流,编码) 但 “流” 是一个抽象的!我应该在哪里放置他将读取的文件的路径?
从ANSI到ASCII的直接转换可能不总是可能的,因为ANSI是ASCII的超集。
您可以尝试使用Encoding
转换为UTF-8,虽然:
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,但并没有真正意义,因为:
UPDATE:
针对更新的问题,你可以使用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
来选择不同的代码页。
好的答案,特别是指出你可以使用静态File方法,而不需要直接涉及FileStreams或缓冲区。 – Noldorin 2009-04-09 12:14:49
为什么你认为你想将它转换为ASCII?答案可能会揭示你实际上应该将其转换为... – Guffa 2009-04-09 13:54:26