FileNotFoundException là ngoại lệ được ném khi cố gắng truy cập file không tồn tại trên đĩa. Thuộc namespace System.IO, kế thừa từ IOException.
Ví dụ gây ra exception
using (StreamReader reader = new StreamReader("new.txt"))
{
reader.ReadToEnd(); // Ném FileNotFoundException nếu new.txt không tồn tại
}
Mã nguồn minh họa
using System.IO;
using System;
class Program
{
static void Main()
{
using (StreamReader reader = new StreamReader("new.txt"))
{
reader.ReadToEnd();
}
}
}
Kết quả (Exception)
Unhandled Exception: System.IO.FileNotFoundException: Could not find file '...'
Xử lý ngoại lệ (Try-Catch)
try
{
using (StreamReader reader = new StreamReader("new.txt"))
{
string content = reader.ReadToEnd();
Console.WriteLine(content);
}
}
catch (FileNotFoundException ex)
{
Console.WriteLine($"File không tồn tại: {ex.FileName}");
Console.WriteLine($"Message: {ex.Message}");
}
catch (IOException ex)
{
Console.WriteLine($"Lỗi I/O: {ex.Message}");
}
Kiểm tra trước khi mở (Best Practice)
string path = "new.txt";
if (File.Exists(path))
{
using (var reader = new StreamReader(path))
{
string content = reader.ReadToEnd();
// Xử lý content
}
}
else
{
Console.WriteLine("File không tồn tại.");
}
Thuộc tính quan trọng của FileNotFoundException
| Thuộc tính | Mô tả |
|---|---|
FileName | Tên file gây ra lỗi |
Message | Mô tả lỗi chi tiết |
HResult | Mã lỗi HRESULT (0x80070002 = FILE_NOT_FOUND) |
Lưu ý
- Kiểm tra
File.Existstrước có điều kiện đua (race condition) - file có thể bị xóa giữa lúc check và lúc mở. - Best practice: Try-Catch quanh thao tác mở file (EAFP - Easier to Ask Forgiveness than Permission).
File.Open,File.ReadAllText,StreamReaderđều ném exception này.