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áp | Namespace | Đặc điểm |
|---|---|---|
File.ReadAllText(path) | System.IO | Đơn giản nhất, tự mở/đóng, trả về string |
File.ReadAllLines(path) | System.IO | Trả về string[] (mỗi dòng) |
StreamReader.ReadToEnd() | System.IO | Kiể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.