Computer >> Máy Tính >  >> Lập trình >> C#

Làm thế nào để lấy tất cả các thư mục và thư mục con bên trong một đường dẫn trong C #?

Để lấy các thư mục, C # cung cấp một phương thức Directory.GetDirectories. Phương thức Directory.GetDirectories trả về tên của các thư mục con (bao gồm cả đường dẫn của chúng) khớp với mẫu tìm kiếm được chỉ định trong thư mục được chỉ định và tùy chọn tìm kiếm các thư mục con.

Trong ví dụ dưới đây, * khớp với 0 hoặc nhiều ký tự ở vị trí đó. SearchOption TopDirectoryOnly. Chỉ lấy các thư mục trên cùng và SearchOption AllDirectories. Lấy tất cả các thư mục trên cùng và thư mục con.

Lưu ý: RootPath sẽ là rootPath hệ thống của bạn, vì vậy hãy tạo một thư mục thử nghiệm và sử dụng rootPath một cách tích lũy.

Ví dụ 1

static void Main (string[] args) {
   string rootPath = @"C:\Users\Koushik\Desktop\TestFolder";
   string[] dirs = Directory.GetDirectories(rootPath, "*", SearchOption.TopDirectoryOnly);

   foreach (string dir in dirs) {
      Console.WriteLine (dir);
   }
   Console.ReadLine ();
}

Đầu ra

C:\Users\Koushik\Desktop\TestFolder\TestFolderMain
C:\Users\Koushik\Desktop\TestFolder\TestFolderMain 1
C:\Users\Koushik\Desktop\TestFolder\TestFolderMain 2

Ví dụ 2

static void Main (string[] args) {
   string rootPath = @"C:\Users\Koushik\Desktop\TestFolder";
   string[] dirs = Directory.GetDirectories(rootPath, "*", SearchOption.AllDirectories);

   foreach (string dir in dirs) {
      Console.WriteLine (dir);
   }
   Console.ReadLine ();
}

Đầu ra

C:\Users\Koushik\Desktop\TestFolder\TestFolderMain
C:\Users\Koushik\Desktop\TestFolder\TestFolderMain 1
C:\Users\Koushik\Desktop\TestFolder\TestFolderMain 2
C:\Users\Koushik\Desktop\TestFolder\TestFolderMain 2\TestFolderMainSubDirectory