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ức | Mô tả |
|---|---|
Directory.GetDirectories | Lấy thư mục con |
Directory.GetFiles | Lấy file trong thư mục |
Directory.GetFileSystemEntries | Lấy cả file và thư mục |
Directory.Move | Di chuyển thư mục |
Directory.Delete | Xóa thư mục |
DirectoryInfo.GetDirectories | Instance method |
DirectoryInfo.GetFiles | Instance method |
Lưu ý
Directory.Existstrả vềfalsecho 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.