首页主机资讯c# readline如何处理不同编码的文件

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

时间2024-06-24 18:30:03发布访客分类主机资讯浏览666
导读:在C#中,可以使用StreamReader类来读取不同编码的文件,并根据需要进行处理。下面是一个示例代码,演示如何使用StreamReader来读取不同编码的文件: using System; using System.IO; using...

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

声明:本文内容由网友自发贡献,本站不承担相应法律责任。对本内容有异议或投诉,请联系2913721942#qq.com核实处理,我们将尽快回复您,谢谢合作!


若转载请注明出处: c# readline如何处理不同编码的文件
本文地址: https://pptw.com/jishu/683768.html
c# readline如何读取大文件 c# readline怎样实现密码输入功能

游客 回复需填写必要信息