Để đọc các tệp văn bản, hãy sử dụng lớp StreamReader trong C #.
Thêm tên của tệp bạn muốn đọc -
StreamReader sr = new StreamReader("hello.txt"); Sử dụng phương thức ReadLine () và lấy nội dung của tệp trong một chuỗi -
using (StreamReader sr = new StreamReader("hello.txt")) {
str = sr.ReadLine();
}
Console.WriteLine(str); Hãy cho chúng tôi xem đoạn mã sau -
Ví dụ
using System.IO;
using System;
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);
}
} Nó tạo tệp “hello.text” và thêm văn bản vào đó. Sau đó, bằng cách sử dụng lớp StreamReader, nó sẽ đọc dòng đầu tiên trong tệp của bạn -
Đầu ra
Sau đây là kết quả đầu ra.
Hello