หากต้องการเปิดไฟล์ข้อความธรรมดา ให้ใช้คลาส StreamReader ต่อไปนี้จะเปิดไฟล์สำหรับอ่าน -
StreamReader sr = new StreamReader("d:/new.txt") ตอนนี้แสดงเนื้อหาของไฟล์ -
while ((line = sr.ReadLine()) != null) {
Console.WriteLine(line);
} นี่คือรหัส −
ตัวอย่าง
using System;
using System.IO;
namespace FileApplication {
class Program {
static void Main(string[] args) {
try {
using (StreamReader sr = new StreamReader("d:/new.txt")) {
string line;
// Read and display lines from the file until
// the end of the file is reached.
while ((line = sr.ReadLine()) != null) {
Console.WriteLine(line);
}
}
} catch (Exception e) {
// Let the user know what went wrong.
Console.WriteLine("The file could not be read:");
Console.WriteLine(e.Message);
}
Console.ReadKey();
}
}
} ผลลัพธ์
The file could not be read: Could not find a part of the path "/home/cg/root/4281363/d:/new.txt".