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

DirectoryNotFoundException trong C#

DirectoryNotFoundException được ném khi cố gắng truy cập thư mục (directory) không tồn tại. Thuộc System.IO, kế thừa từ IOException.

Ví dụ gây ra exception

Directory.GetDirectories(@"D:\new\");  // Ném exception nếu D:\new không tồn tại

Mã nguồn minh họa

using System.IO;
using System;

class Program
{
    static void Main()
    {
        Directory.GetDirectories(@"D:\new\");
    }
}

Kết quả (Exception)

Unhandled Exception: System.IO.DirectoryNotFoundException: Could not find a part of the path 'D:\new\'

Xử lý ngoại lệ

try
{
    string[] dirs = Directory.GetDirectories(@"D:\new\");
    foreach (string dir in dirs) Console.WriteLine(dir);
}
catch (DirectoryNotFoundException ex)
{
    Console.WriteLine($"Thư mục không tồn tại: {ex.Message}");
}
catch (UnauthorizedAccessException ex)
{
    Console.WriteLine($"Không có quyền truy cập: {ex.Message}");
}

Kiểm tra trước khi truy cập

string path = @"D:\new\";

if (Directory.Exists(path))
{
    string[] dirs = Directory.GetDirectories(path);
    // Xử lý...
}
else
{
    Console.WriteLine("Thư mục không tồn tại.");
}

Phương thức thường ném DirectoryNotFoundException

Phương thứcMô tả
Directory.GetDirectoriesLấy thư mục con
Directory.GetFilesLấy file trong thư mục
Directory.GetFileSystemEntriesLấy cả file và thư mục
Directory.MoveDi chuyển thư mục
Directory.DeleteXóa thư mục
DirectoryInfo.GetDirectoriesInstance method
DirectoryInfo.GetFilesInstance method

Lưu ý

  • Directory.Exists trả về false cho cả file và thư mục không tồn tại.
  • Race condition tương tự File - ưu tiên try-catch.
  • Trên Linux/macOS, phân biệt chữ hoa/thường trong đường dẫn.
  • Path quá dài (>260 chars trên Windows cũ) cũng có thể ném exception này.