ใช้เมธอด File.ReadAllText() เพื่ออ่านเนื้อหาทั้งหมดของไฟล์ข้อความเป็นสตริงเดียว เหมาะสำหรับไฟล์ขนาดเล็กถึงปานกลาง
ขั้นตอน
- กำหนดพาธไฟล์
- เรียก
File.ReadAllText(path)
ตัวอย่างโค้ดเต็ม
using System;
using System.IO;
public class Demo
{
public static void Main()
{
string myPath = "hello.txt";
string allLines = File.ReadAllText(myPath);
Console.WriteLine(allLines);
}
}
ผลลัพธ์ (ถ้า hello.txt มีเนื้อหา)
One Two Three
คำเตือน: สำหรับไฟล์ขนาดใหญ่มาก ควรใช้ StreamReader อ่านทีละบรรทัดเพื่อประหยัดหน่วยความจำ