ใช้วิธี ReadToEnd() เพื่ออ่านเนื้อหาของไฟล์ในสตริง
ตั้งค่าภายใต้ StreamReader และอ่านไฟล์ -
using (StreamReader sr = new StreamReader("new.txt")){
string res = sr.ReadToEnd();
Console.WriteLine(res);
} ต่อไปนี้เป็นรหัสที่สมบูรณ์ -
ตัวอย่าง
using System.IO;
using System;
public class Demo {
public static void Main() {
using (StreamWriter sw = new StreamWriter("new.txt")) {
sw.WriteLine("One");
sw.WriteLine("Two");
}
using (StreamReader sr = new StreamReader("new.txt")) {
string res = sr.ReadToEnd();
Console.WriteLine(res);
}
}
} มันสร้างไฟล์ "new.text" และเพิ่มข้อความลงไป หลังจากนั้นโดยใช้คลาส StreamReader และเมธอด ReadToEnd() จะอ่านเนื้อหาของไฟล์เป็นสตริง -
ผลลัพธ์
ต่อไปนี้เป็นผลลัพธ์
One Two