การจับข้อยกเว้น FileNotFoundException ใน C#
FileNotFoundException เกิดขึ้นเมื่อพยายามเข้าถึงไฟล์ที่ไม่มีอยู่จริง (Path ผิด, ไฟล์ถูกลบ, Permission ไม่พอ)
ตัวอย่างที่ทำให้เกิด Exception
using (StreamReader reader = new StreamReader("new.txt")) // ไฟล์ไม่มีอยู่
{
string content = reader.ReadToEnd(); // โยน FileNotFoundException
}
การจับข้อยกเว้นด้วย Try-Catch
using System;
using System.IO;
class Program
{
static void Main()
{
try
{
using (StreamReader reader = new StreamReader("new.txt"))
{
string content = reader.ReadToEnd();
Console.WriteLine(content);
}
}
catch (FileNotFoundException ex)
{
Console.WriteLine("File Not Found!");
Console.WriteLine($"File: {ex.FileName}");
Console.WriteLine($"Message: {ex.Message}");
}
catch (DirectoryNotFoundException ex)
{
Console.WriteLine("Directory Not Found!");
}
catch (IOException ex)
{
Console.WriteLine($"IO Error: {ex.Message}");
}
}
}
ผลลัพธ์ (เมื่อไฟล์ไม่มี)
File Not Found!
File: new.txt
Message: Could not find file '...\\new.txt'.
Best Practices
- ตรวจสอบก่อนเปิด:
if (File.Exists(path))แต่มี Race Condition (TOCTOU) - Try-Catch เป็นหลัก เพราะจับได้ทั้ง FileNotFound, Permission, Sharing Violation
- จับ Exception เฉพาะเจาะจงก่อน (FileNotFoundException) แล้วค่อยจับ Base Class (IOException, Exception)
- Logging บันทึก Stack Trace สำหรับ Debug
โครงสร้าง Exception Hierarchy
Exception
└── SystemException
└── IOException
├── FileNotFoundException
├── DirectoryNotFoundException
├── DriveNotFoundException
├── PathTooLongException
└── ...