หากไม่มีไฟล์ที่คุณกำลังพยายามค้นหาอยู่ แสดงว่า FileNotFoundException เกิดขึ้น
ในที่นี้ เรากำลังพยายามค้นหาไฟล์ที่ไม่มีอยู่โดยใช้วิธี StreamReader()
reader = new StreamReader("new.txt")) ในการอ่าน เราได้ใช้วิธีดังต่อไปนี้ -
reader.ReadToEnd();
ให้เราดูรหัสที่สมบูรณ์
ตัวอย่าง
using System.IO;
using System;
class Program {
static void Main() {
using (StreamReader reader = new StreamReader("new.txt")) {
reader.ReadToEnd();
}
}
} รหัสด้านบนจะสร้างข้อยกเว้นต่อไปนี้เนื่องจากไม่มีไฟล์ “new.txt”
Unhandled Exception: System.IO.FileNotFoundException: Could not find file …