Phương thức Environment.GetLogicalDrives() trả về mảng chuỗi chứa các ổ đĩa logic trên hệ thống (ví dụ: "C:\\", "D:\\").
Ví dụ cơ bản
string[] drives = Environment.GetLogicalDrives();
// drives = ["C:\\", "D:\\", "E:\\"]
Mã nguồn hoàn chỉnh
using System;
using System.IO;
namespace Demo
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine(string.Join(",", Environment.GetLogicalDrives()));
}
}
}
Kết quả (ví dụ Linux container)
/,/etc/resolv.conf,/etc/hostname,/etc/hosts,/run/secrets,/home/cg/root
Lưu ý quan trọng
- Trên Windows: Trả về ổ đĩa như
C:\\,D:\\. - Trên Linux/macOS: Trả về các mount point (/, /home, /mnt/...), không phải ổ đĩa vật lý.
- Kết quả phụ thuộc môi trường chạy (container, VM, bare metal).
Kết hợp với DriveInfo để lấy chi tiết
foreach (string drivePath in Environment.GetLogicalDrives())
{
try
{
DriveInfo drive = new DriveInfo(drivePath);
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");
}
}
catch (Exception ex)
{
Console.WriteLine($"{drivePath} - Error: {ex.Message}");
}
}
Phương thức liên quan
| Phương thức | Mô tả |
|---|---|
Environment.GetLogicalDrives() | Mảng string tên ổ đĩa |
DriveInfo.GetDrives() | Mảng DriveInfo object (có sẵn thuộc tính chi tiết) |
Khuyến khích: Dùng DriveInfo.GetDrives() trực tiếp thay vì GetLogicalDrives + new DriveInfo.