Dùng class DriveInfo (namespace System.IO) để lấy thông tin ổ đĩa: dung lượng trống, tổng dung lượng, kiểu ổ đĩa, v.v.
Ví dụ minh họa
using System;
using System.IO;
class Program
{
static void Main()
{
// Lấy thông tin ổ C:
DriveInfo drive = new DriveInfo("C");
if (drive.IsReady)
{
long freeBytes = drive.AvailableFreeSpace;
long totalBytes = drive.TotalSize;
long usedBytes = totalBytes - freeBytes;
double freeGB = freeBytes / (1024.0 * 1024 * 1024);
double totalGB = totalBytes / (1024.0 * 1024 * 1024);
double percentFree = (double)freeBytes / totalBytes * 100;
Console.WriteLine($"Ổ đĩa: {drive.Name}");
Console.WriteLine($"Tổng dung lượng: {totalGB:F2} GB");
Console.WriteLine($"Dung lượng trống: {freeGB:F2} GB ({percentFree:F1}%)");
Console.WriteLine($"Đã dùng: {totalGB - freeGB:F2} GB");
Console.WriteLine($"Hệ thống file: {drive.DriveFormat}");
Console.WriteLine($"Loại ổ: {drive.DriveType}");
}
else
{
Console.WriteLine("Ổ đĩa không sẵn sàng (có thể là ổ CD trống, ổ mạng mất kết nối...)");
}
}
}
Kết quả đầu ra (ví dụ)
Ổ đĩa: C:\ Tổng dung lượng: 476.94 GB Dung lượng trống: 123.45 GB (25.9%) Đã dùng: 353.49 GB Hệ thống file: NTFS Loại ổ: Fixed
Lưu ý: Luôn kiểm tra IsReady trước khi truy cập thuộc tính để tránh exception trên ổ đĩa removable.