Giới thiệu
StreamWriter ghi text vào stream (file, memory, network). Kế thừa TextWriter, hỗ trợ encoding, auto-flush, buffer.
Ví dụ cơ bản
using (StreamWriter sw = new StreamWriter("hello.txt"))
{
sw.WriteLine("Hello");
sw.WriteLine("World");
}
Ví dụ hoàn chỉnh
using System.IO;
public class Program
{
public static void Main()
{
using (StreamWriter sw = new StreamWriter("hello.txt"))
{
sw.WriteLine("Hello");
sw.WriteLine("World");
}
}
}
Kết quả (nội dung file hello.txt)
Hello World
Các phương thức ghi chính
| Phương thức | Mô tả |
|---|---|
Write(value) | Ghi không newline |
WriteLine(value) | Ghi + newline |
WriteAsync | Async version |
Flush() | Đẩy buffer ra stream |
Constructor phổ biến
new StreamWriter(path)- ghi đè (overwrite), UTF-8 no BOM.new StreamWriter(path, append)- append nếu true.new StreamWriter(path, append, encoding)- chỉ định encoding.new StreamWriter(stream, encoding)- ghi vào stream (MemoryStream, NetworkStream).
Ví dụ Append (ghi tiếp)
using (StreamWriter sw = new StreamWriter("log.txt", append: true))
{
sw.WriteLine($"[{DateTime.Now}] Application started");
}
Lưu ý
- Luôn dùng
usingđể Dispose (flush + close handle). AutoFlush = trueđể flush sau mỗi Write (chậm hơn).- Mặc định encoding UTF-8 without BOM. Dùng
Encoding.UTF8(có BOM) hoặcEncoding.Unicode(UTF-16) nếu cần. - Đối với file lớn, cân nhắc
File.AppendAllLineshoặcFile.WriteAllLines.