Sử dụng phương thức ReadToEnd () để đọc nội dung của tệp trong một chuỗi.
Đặt nó trong StreamReader và đọc tệp -
using (StreamReader sr = new StreamReader("new.txt")){
string res = sr.ReadToEnd();
Console.WriteLine(res);
} Sau đây là mã hoàn chỉnh -
Ví dụ
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);
}
}
} Nó tạo tệp “new.text” và thêm văn bản vào đó. Sau đó, sử dụng lớp StreamReader và phương thức ReadToEnd (), nó đọc nội dung của tệp thành một chuỗi -
Đầu ra
Sau đây là kết quả đầu ra.
One Two