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ính | Kiểu | Mô tả |
|---|---|---|
Name | string | Tên ổ (ví dụ: "C:\\") |
VolumeLabel | string | Nhãn ổ đĩa |
AvailableFreeSpace | long | Dung lượng trống khả dụng (bytes) |
TotalFreeSpace | long | Tổng dung lượng trống (bytes) |
TotalSize | long | Tổng dung lượng ổ (bytes) |
DriveFormat | string | Hệ thống file (NTFS, FAT32, exFAT...) |
DriveType | DriveType | Loại ổ: Fixed, Removable, Network, CDRom, Ram, Unknown |
IsReady | bool | Ổ 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.
AvailableFreeSpacetính đến quota người dùng,TotalFreeSpacelà vật lý trống.