Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> C#

FileNotFoundException trong C#

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ínhMô tả
FileNameTên file gây ra lỗi
MessageMô tả lỗi chi tiết
HResultMã lỗi HRESULT (0x80070002 = FILE_NOT_FOUND)

Lưu ý

  • Kiểm tra File.Exists trướ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.