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

Lấy thư mục gốc của ổ đĩa trong C#


Giới thiệu

Thuộc tính RootDirectory của lớp DriveInfo trả về một đối tượng DirectoryInfo đại diện cho thư mục gốc (root directory) của ổ đĩa.

Ví dụ cơ bản

DriveInfo dInfo = new DriveInfo("C");
Console.WriteLine(dInfo.RootDirectory); // C:\

Ví dụ hoàn chỉnh

using System;
using System.IO;

public class Demo
{
    public static void Main()
    {
        DriveInfo dInfo = new DriveInfo("C");
        Console.WriteLine("Root Directory: " + dInfo.RootDirectory);
    }
}

Kết quả

C:\

Ứng dụng thực tế

Đối tượng DirectoryInfo trả về cho phép thực hiện các thao tác:

  • Liệt kê thư mục con: root.GetDirectories()
  • Liệt kê file: root.GetFiles()
  • Kiểm tra tồn tại: root.Exists
  • Tạo thư mục: root.CreateSubdirectory("NewFolder")

Ví dụ mở rộng

DriveInfo dInfo = new DriveInfo("C");
if (dInfo.IsReady)
{
    DirectoryInfo root = dInfo.RootDirectory;
    Console.WriteLine($"Thư mục gốc: {root.FullName}");
    Console.WriteLine($"Số thư mục con: {root.GetDirectories().Length}");
    Console.WriteLine($"Số file: {root.GetFiles().Length}");
}

Lưu ý

  • Trên Windows, kết quả thường là "C:\", "D:\", v.v.
  • Trên Linux, nếu khởi tạo new DriveInfo("/"), kết quả sẽ là "/".
  • Thuộc tính này hữu ích khi cần duyệt toàn bộ cây thư mục của ổ đĩa.