Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> C#

การดึงชื่อไดเรกทอรีราก (Root Directory) ของไดรฟ์ใน C#

คุณสมบัติ RootDirectory ของคลาส DriveInfo คืนค่าออบเจกต์ DirectoryInfo ที่แทนไดเรกทอรีรากของไดรฟ์นั้นๆ ทำให้สามารถดำเนินการกับไฟล์และโฟลเดอร์ในไดรฟ์ได้ทันที

รูปแบบการใช้งาน

DriveInfo drive = new DriveInfo("C");
DirectoryInfo root = drive.RootDirectory;
Console.WriteLine(root.FullName); // C:\

โค้ดตัวอย่างสมบูรณ์

using System;
using System.IO;

public class Demo
{
    public static void Main()
    {
        try
        {
            DriveInfo drive = new DriveInfo("C");
            
            Console.WriteLine($"ไดรฟ์: {drive.Name}");
            Console.WriteLine($"ไดเรกทอรีราก: {drive.RootDirectory.FullName}");
            Console.WriteLine($"มีอยู่จริง: {drive.RootDirectory.Exists}");
            
            // แสดงไฟล์/โฟลเดอร์ในไดเรกทอรีราก (5 รายการแรก)
            if (drive.IsReady && drive.RootDirectory.Exists)
            {
                Console.WriteLine("\nเนื้อหาในไดเรกทอรีราก (5 รายการแรก):");
                var items = drive.RootDirectory.GetFileSystemInfos().Take(5);
                foreach (var item in items)
                {
                    string type = item is DirectoryInfo ? "[โฟลเดอร์]" : "[ไฟล์]";
                    Console.WriteLine($"  {type} {item.Name}");
                }
            }
        }
        catch (Exception ex)
        {
            Console.WriteLine($"ข้อผิดพลาด: {ex.Message}");
        }
    }
}

ผลลัพธ์ตัวอย่าง

ไดรฟ์: C:\
ไดเรกทอรีราก: C:\
มีอยู่จริง: True

เนื้อหาในไดเรกทอรีราก (5 รายการแรก):
  [โฟลเดอร์] Program Files
  [โฟลเดอร์] Users
  [โฟลเดอร์] Windows
  [ไฟล์] pagefile.sys
  [ไฟล์] hiberfil.sys

การใช้งาน DirectoryInfo ที่ได้จาก RootDirectory

DirectoryInfo root = drive.RootDirectory;

// สร้างโฟลเดอร์ใหม่
root.CreateSubfolder("MyApp");

// ค้นหาไฟล์
FileInfo[] configs = root.GetFiles("*.config", SearchOption.AllDirectories);

// ดึงโฟลเดอร์ย่อย
DirectoryInfo[] subDirs = root.GetDirectories();

การใช้งานข้ามแพลตฟอร์ม

// Linux/macOS
DriveInfo drive = new DriveInfo("/");
DirectoryInfo root = drive.RootDirectory; // จะได้ /

DriveInfo drive2 = new DriveInfo("/home");
DirectoryInfo root2 = drive2.RootDirectory; // จะได้ /home

ข้อควรระวัง

  • คืนค่า DirectoryInfo ไม่ใช่สตริง - ต้องใช้ .FullName หรือ .Name เพื่อได้พาธ
  • ต้องตรวจสอบ IsReady และ Exists ก่อนใช้งาน
  • อาจต้องการสิทธิ์ Administrator เพื่อเข้าถึงบางไดเรกทอรีใน C:\