我正在尝试逐行读取文件并写入另一个文件。但是,在写入文件后,某些字符(例如引号"
和撇号'
)已替换为问号(?)。我该如何解决?
public static void Main(string[] args) {
int counter = 0;
string line;
// Read the file and display it line by line.
System.IO.StreamReader file = new System.IO.StreamReader("C:\\Users\\mypc\\Desktop\\test.txt");
System.IO.StreamWriter OutPutFile = new System.IO.StreamWriter("C:\\Users\\mypc\\Desktop\\out.txt");
System.IO.StreamWriter lineOutPutFile = new System.IO.StreamWriter("C:\\Users\\mypc\\Desktop\\lineoutput.txt");
while ((line = file.ReadLine()) != null) {
OutPutFile.Write(line);
OutPutFile.Write(" ");
Console.Write(line);
Console.Write(" ");
// Call your function here
counter++;
}
file.Close();
OutPutFile.Close();
lineOutPutFile.Close();
}
答案 0 :(得分:1)
StreamReader专为使用特定编码的字符输入而设计,因此您可以指定以下编码
new StreamReader(fs, System.Text.Encoding.UTF8); // UTF-8 that is the most common form of unicode encoding
您还可以尝试使用默认编码,该编码使用当前系统的ANSI代码页。
new StreamReader(fs, System.Text.Encoding.Default);
从MSDN :
编码是转换一组Unicode字符的过程 成字节序列
编码类允许错误更改为“?”性格,为什么要使用参见?在您的输出中
PS: 您可以打开记事本,并确定记事本用于文件的编码
注意: 在使用StreamReader和StreamWriter对象释放其使用的所有资源后,请记住处理它们。
参考文献: https://docs.microsoft.com/en-us/dotnet/api/system.text.encoding?view=netframework-4.8