ภาพรวม
StreamReader ใช้อ่านข้อความจากไฟล์ (text file) แบบลำดับ (sequential) เมธอดหลักคือ ReadLine() อ่านทีละบรรทัด
รูปแบบการใช้งาน
using (StreamReader sr = new StreamReader("hello.txt"))
{
string line = sr.ReadLine(); // อ่านบรรทัดแรก
Console.WriteLine(line);
}
ตัวอย่างโค้ดเต็ม (สร้างไฟล์ แล้วอ่านบรรทัดแรก)
using System;
using System.IO;
public class Program
{
public static void Main()
{
string str;
using (StreamWriter sw = new StreamWriter("hello.txt"))
{
sw.WriteLine("Hello");
sw.WriteLine("World");
}
using (StreamReader sr = new StreamReader("hello.txt"))
{
str = sr.ReadLine(); // อ่านบรรทัดแรกเท่านั้น
}
Console.WriteLine(str);
}
}
ผลลัพธ์
Hello
เมธอดอ่านที่เกี่ยวข้อง
ReadLine()- อ่านบรรทัด (จนกว่าจะเจอ newline) คืน null หากจบไฟล์ReadToEnd()- อ่านทั้งไฟล์ที่เหลือRead()- อ่านทีละ char (คืน int) -1 หากจบไฟล์ReadBlock()- อ่านทีละบล็อก (char array) มีประสิทธิภาพดีกว่าPeek()- ดู char ถัดไปโดยไม่กิน (คืน int)
อ่านทุกบรรทัด
using (var sr = new StreamReader("file.txt"))
{
string line;
while ((line = sr.ReadLine()) != null)
Console.WriteLine(line);
}