ประการแรก ใช้ GetDrives เพื่อรับชื่อไดรฟ์ทั้งหมด -
var drv = DriveInfo.GetDrives();
วนซ้ำเพื่อรับชื่อของไดรฟ์ทั้งหมดในระบบ -
foreach (DriveInfo dInfo in drv) {
Console.WriteLine(dInfo.Name);
} ให้เราดูรหัสที่สมบูรณ์ -
ตัวอย่าง
using System;
using System.Linq;
using System.IO;
public class Demo {
public static void Main() {
var drv = DriveInfo.GetDrives();
foreach (DriveInfo dInfo in drv) {
Console.WriteLine(dInfo.Name);
}
}
} ผลลัพธ์
/etc/resolv.conf /etc/hostname /etc/hosts /run/secrets /home/cg/root
หมายเหตุ:ผลลัพธ์จะแตกต่างกันไปตามระบบปฏิบัติการที่แตกต่างกัน เอาต์พุตด้านบนแสดงบน Linux OS
มันจะให้ผลลัพธ์ต่อไปนี้บน Windows OS:
C:\ D:\ E:\