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

Liệt kê thư mục và tập tin bằng C#

Lớp Directory trong C# có nhiều phương thức thao tác trên thư mục và thư mục con.

STTPhương thức & Mô tả
1CreateDirectory(String) - Tạo tất cả thư mục theo đường dẫn.
2CreateDirectoryDirectorySecurity(String) - Tạo thư mục với bảo mật Windows.
3Delete(String) - Xóa thư mục rỗng.
4DeleteBoolean(String) - Xóa thư mục và nội dung nếu chỉ định.
5EnumerateDirectories(String) - Trả về tập tên thư mục.
6EnumerateDirectories(String, String) - Trả về thư mục khớp mẫu tìm kiếm.

Để lấy tên thư mục, dùng EnumerateDirectories. Thiết lập thư mục bằng DirectoryInfo:

DirectoryInfo info = new DirectoryInfo(@"D:/new");

Tính tổng kích thước file:

long totalSize = info.EnumerateFiles().Sum(file => file.Length);

Lấy danh sách thư mục con:

info.EnumerateDirectories()