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