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

Lấy thông tin ổ đĩa (Drive Information) trong C#

Lớp DriveInfo trong System.IO cung cấp thông tin chi tiết về các ổ đĩa (drives) trên hệ thống: tên, nhãn, dung lượng trống, tổng dung lượng, hệ thống file, loại ổ.

Các thuộc tính chính

Thuộc tínhKiểuMô tả
NamestringTên ổ (ví dụ: "C:\\")
VolumeLabelstringNhãn ổ đĩa
AvailableFreeSpacelongDung lượng trống khả dụng (bytes)
TotalFreeSpacelongTổng dung lượng trống (bytes)
TotalSizelongTổng dung lượng ổ (bytes)
DriveFormatstringHệ thống file (NTFS, FAT32, exFAT...)
DriveTypeDriveTypeLoại ổ: Fixed, Removable, Network, CDRom, Ram, Unknown
IsReadyboolỔ có sẵn sàng đọc/ghi không

Mã nguồn hoàn chỉnh

using System.IO;
using System;

class Program
{
    static void Main()
    {
        DriveInfo driveInfo = new DriveInfo("D");
        
        Console.WriteLine("Name: " + driveInfo.Name);
        Console.WriteLine("VolumeLabel: " + driveInfo.VolumeLabel);
        Console.WriteLine("AvailableFreeSpace: " + driveInfo.AvailableFreeSpace);
        Console.WriteLine("TotalFreeSpace: " + driveInfo.TotalFreeSpace);
        Console.WriteLine("TotalSize: " + driveInfo.TotalSize);
        Console.WriteLine("DriveFormat: " + driveInfo.DriveFormat);
        Console.WriteLine("DriveType: " + driveInfo.DriveType);
    }
}

Kết quả (ví dụ)

D:
NTFS
76767677788
76767677788
45463434799
NTFS
Fixed

Liệt kê tất cả ổ đĩa

foreach (DriveInfo drive in DriveInfo.GetDrives())
{
    if (drive.IsReady)
    {
        Console.WriteLine($"{drive.Name} ({drive.DriveType}) - {drive.DriveFormat}");
        Console.WriteLine($"  Free: {drive.AvailableFreeSpace / 1e9:F1} GB / {drive.TotalSize / 1e9:F1} GB");
    }
    else
    {
        Console.WriteLine($"{drive.Name} - Not ready");
    }
}

Lưu ý

  • Kết quả khác nhau tùy hệ điều hành (Windows/Linux/macOS).
  • Trên Linux, DriveInfo.GetDrives() trả về các mount point.
  • Cần quyền admin để đọc một số ổ hệ thống.
  • AvailableFreeSpace tính đến quota người dùng, TotalFreeSpace là vật lý trống.