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

Sử dụng lớp Directory trong C#


Lớp Directory trong C# (namespace System.IO) cung cấp các phương thức static để thao tác với cấu trúc thư mục: tạo, di chuyển, xóa, liệt kê, lấy thông tin.

Các phương thức chính

Phương thứcMô tả
CreateDirectory(path)Tạo thư mục và các thư mục con (recursive)
Delete(path)Xóa thư mục rỗng
Delete(path, true)Xóa thư mục và toàn bộ nội dung (recursive)
Exists(path)Kiểm tra thư mục tồn tại
GetCreationTime(path)Lấy thời gian tạo
GetCurrentDirectory()Lấy thư mục làm việc hiện tại
GetFiles(path)Lấy danh sách file (có thể lọc pattern)
GetDirectories(path)Lấy danh sách thư mục con
Move(source, dest)Di chuyển/đổi tên thư mục
GetParent(path)Lấy thư mục cha

Ví dụ: Liệt kê file trong thư mục

using System;
using System.IO;

class Program
{
    static void Main()
    {
        string path = @"D:\"; // Hoặc Environment.CurrentDirectory
        
        if (Directory.Exists(path))
        {
            Console.WriteLine("Các file trong {0}:", path);
            string[] files = Directory.GetFiles(path);
            
            foreach (string file in files)
                Console.WriteLine(file);
        }
        else
        {
            Console.WriteLine("Thư mục không tồn tại");
        }
    }
}

Ví dụ: Tìm file theo pattern

// Tất cả file .txt
string[] txtFiles = Directory.GetFiles(path, "*.txt");

// Tìm đệ quy (tất cả thư mục con)
string[] allTxt = Directory.GetFiles(path, "*.txt", SearchOption.AllDirectories);

// Lấy thông tin chi tiết (FileInfo)
var fileInfos = new DirectoryInfo(path).GetFiles("*.txt");

Ví dụ: Tạo/xóa thư mục

string newDir = @"D:\TestFolder\SubFolder";

// Tạo (tự tạo cả thư mục cha)
Directory.CreateDirectory(newDir);

if (Directory.Exists(newDir))
    Console.WriteLine("Đã tạo thành công");

// Xóa thư mục rỗng
Directory.Delete(newDir);

// Xóa thư mục có nội dung
Directory.Delete(newDir, true);

Lưu ý

  • Tất cả phương thức đều static
  • Cần using System.IO;
  • Xử lý exception: UnauthorizedAccessException, DirectoryNotFoundException, IOException
  • Path có thể dùng @ verbatim string hoặc escape \\