c# readline如何处理不同编码的文件

   2024-10-08 4080
核心提示:在C#中,可以使用StreamReader类来读取不同编码的文件,并根据需要进行处理。下面是一个示例代码,演示如何使用StreamReader来读

在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以及指定编码的文件,并分别指定了相应的编码格式。通过指定不同的编码格式,可以确保正确地读取文件内容并进行处理。

 
举报打赏
 
更多>同类维修大全
推荐图文
推荐维修大全
点击排行

网站首页  |  关于我们  |  联系方式网站留言    |  赣ICP备2021007278号