c# readline如何處理不同編碼的文件

c#
小樊
99
2024-06-24 10:55:28

在C#中,可以使用StreamReader類來(lái)讀取不同編碼的文件,并根據(jù)需要進(jìn)行處理。下面是一個(gè)示例代碼,演示如何使用StreamReader來(lái)讀取不同編碼的文件:

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以及指定編碼的文件,并分別指定了相應(yīng)的編碼格式。通過(guò)指定不同的編碼格式,可以確保正確地讀取文件內(nèi)容并進(jìn)行處理。

0