在C#中,可以使用StreamReader类来读取不同编码的文件,并根据需要进行处理。下面是一个示例代码,演示如何使用StreamReader来读取不同编码的文件:
using System; using System.IO; using System.Text; class Program { static void Main() { string filePath = "example.txt"; // 读取UTF-8编码的文件 using (StreamReader sr = new StreamReader(filePath, Encoding.UTF8)) { string line; while ((line = sr.ReadLine()) != null) { Console.WriteLine(line); } } // 读取UTF-16编码的文件 using (StreamReader sr = new StreamReader(filePath, Encoding.Unicode)) { string line; while ((line = sr.ReadLine()) != null) { Console.WriteLine(line); } } // 读取ANSI编码的文件 using (StreamReader sr = new StreamReader(filePath, Encoding.Default)) { string line; while ((line = sr.ReadLine()) != null) { Console.WriteLine(line); } } // 读取指定编码的文件 Encoding encoding = Encoding.GetEncoding("GB2312"); using (StreamReader sr = new StreamReader(filePath, encoding)) { string line; while ((line = sr.ReadLine()) != null) { Console.WriteLine(line); } } } }
在示例代码中,我们使用StreamReader类分别读取了UTF-8、UTF-16、ANSI以及指定编码的文件,并分别指定了相应的编码格式。通过指定不同的编码格式,可以确保正确地读取文件内容并进行处理。