Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> C#

Đọc file với StreamReader trong C#


Giới thiệu

StreamReader đọc text file theo dòng (line by line) hoặc toàn bộ. Kế thừa TextReader, hỗ trợ encoding, buffer.

Ví dụ cơ bản: Đọc 1 dòng

using (StreamReader sr = new StreamReader("hello.txt"))
{
    string str = sr.ReadLine(); // Đọc dòng đầu tiên
    Console.WriteLine(str);
}

Ví dụ hoàn chỉnh (tạo file rồi đọc)

using System;
using System.IO;

public class Program
{
    public static void Main()
    {
        string str;
        using (StreamWriter sw = new StreamWriter("hello.txt"))
        {
            sw.WriteLine("Hello");
            sw.WriteLine("World");
        }
        using (StreamReader sr = new StreamReader("hello.txt"))
        {
            str = sr.ReadLine(); // Chỉ đọc dòng 1
        }
        Console.WriteLine(str); // "Hello"
    }
}

Kết quả

Hello

Đọc toàn bộ file theo dòng

using (StreamReader sr = new StreamReader("hello.txt"))
{
    string line;
    while ((line = sr.ReadLine()) != null)
    {
        Console.WriteLine(line);
    }
}

Các phương thức chính

Phương thứcMô tả
Read()Đọc 1 char (int), -1 nếu EOF
ReadLine()Đọc 1 dòng (không chứa newline), null nếu EOF
ReadToEnd()Đọc hết còn lại, trả về string
ReadBlock()Đọc block char vào buffer
Peek()Xem char tiếp theo không consume

Encoding

// Mặc định UTF-8 (có BOM detection)
new StreamReader("file.txt")
// Tự định encoding
new StreamReader("file.txt", Encoding.GetEncoding("windows-1258"))
// Detect encoding từ BOM
new StreamReader("file.txt", detectEncodingFromByteOrderMarks: true)

Lưu ý

  • Luôn dùng using hoặc try/finally để close stream.
  • ReadLine bỏ qua ký tự newline (\n, \r, \r\n).
  • File lớn: đọc dòng per dòng (streaming) thay vì ReadToEnd.