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

Đọc toàn bộ nội dung file vào string trong C#


Giới thiệu

Phương thức StreamReader.ReadToEnd() đọc toàn bộ nội dung file từ vị trí hiện tại đến cuối, trả về string. Thường dùng trong using block để tự động dispose.

Ví dụ cơ bản

using (StreamReader sr = new StreamReader("new.txt"))
{
    string res = sr.ReadToEnd();
    Console.WriteLine(res);
}

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

using System;
using System.IO;

public class Demo
{
    public static void Main()
    {
        // Tạo file test
        using (StreamWriter sw = new StreamWriter("new.txt"))
        {
            sw.WriteLine("One");
            sw.WriteLine("Two");
        }

        // Đọc toàn bộ
        using (StreamReader sr = new StreamReader("new.txt"))
        {
            string res = sr.ReadToEnd();
            Console.WriteLine(res);
        }
    }
}

Kết quả

One
Two

Các cách đọc file khác

Phương phápNamespaceĐặc điểm
File.ReadAllText(path)System.IOĐơn giản nhất, tự mở/đóng, trả về string
File.ReadAllLines(path)System.IOTrả về string[] (mỗi dòng)
StreamReader.ReadToEnd()System.IOKiểm soát encoding, buffer, streaming
StreamReader.ReadLine()System.IOĐọc dòng per dòng (tiết kiệm RAM)

Ví dụ hiện đại (.NET Core 2.1+)

// Đơn giản nhất
string content = File.ReadAllText("new.txt");

// Với encoding tùy chỉnh
string content = File.ReadAllText("new.txt", Encoding.UTF8);

// Async
string content = await File.ReadAllTextAsync("new.txt");

Lưu ý

  • ReadToEnd đọc toàn bộ vào RAM - cẩn thận với file lớn (>100MB).
  • Mặc định dùng UTF-8. Chỉ định encoding nếu file encoding khác.
  • using đảm bảo Dispose/Close file handle ngay cả khi exception.