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

StreamWriter trong C#


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ứcMô tả
Write(value)Ghi không newline
WriteLine(value)Ghi + newline
WriteAsyncAsync 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ặc Encoding.Unicode (UTF-16) nếu cần.
  • Đối với file lớn, cân nhắc File.AppendAllLines hoặc File.WriteAllLines.