ภาพรวม
StreamWriter ใช้ เขียนข้อความ (text) ลงไฟล์ หรือสตรีมอื่นๆ รองรับ encoding (ค่าเริ่มต้น UTF-8) และ auto-flush
รูปแบบการใช้งาน
using (StreamWriter sw = new StreamWriter("hello.txt"))
{
sw.WriteLine("Hello");
sw.WriteLine("World");
}
ตัวอย่างโค้ดเต็ม
using System.IO;
public class Program
{
public static void Main()
{
using (StreamWriter sw = new StreamWriter("hello.txt"))
{
sw.WriteLine("Hello");
sw.WriteLine("World");
}
}
}
ผลลัพธ์ (ไฟล์ hello.txt)
Hello World
เมธอดหลัก
| เมธอด | คำอธิบาย |
|---|---|
Write(value) | เขียนโดยไม่ขึ้นบรรทัดใหม่ |
WriteLine(value) | เขียนแล้วขึ้นบรรทัดใหม่ |
WriteAsync / WriteLineAsync | เวอร์ชัน async |
Flush() | บังคับเขียน buffer ลงดิสก์ทันที |
AutoFlush property | true = flush หลังทุก Write (ช้ากว่า) |
Encoding
new StreamWriter("file.txt", false, Encoding.UTF8) // false = overwrite, true = append