在处理中文文件时,如果出现乱码,可以考虑使用带有编码方式的文件流。

例如,如果文件编码为UTF-8,可以使用以下方式创建文件流:

FileStream fs = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
StreamReader sr = new StreamReader(fs, Encoding.UTF8);

在读取文件时,使用StreamReader进行读取,同时指定编码方式为UTF-8。

如果是写入文件,同样需要指定编码方式:

FileStream fs = new FileStream(filePath, FileMode.Create, FileAccess.Write, FileShare.ReadWrite);
StreamWriter sw = new StreamWriter(fs, Encoding.UTF8);

在写入文件时,使用StreamWriter进行写入,同时指定编码方式为UTF-8。

通过指定编码方式,可以保证文件的正确读写,避免出现乱码问题

C#文件流中文乱码

原文地址: https://www.cveoy.top/t/topic/hgw5 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录