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

วิธีดึงไฟล์ Sub-files และขนาดไฟล์ใน Directory ด้วย C#

ใช้คลาส System.IO.Directory และ System.IO.FileInfo จาก Namespace System.IO

เมธอดหลัก

  • Directory.GetFiles(path, pattern, SearchOption): คืน Array ของ Path ไฟล์
  • SearchOption.TopDirectoryOnly: ค้นหาเฉพาะโฟลเดอร์บนสุด
  • SearchOption.AllDirectories: ค้นหารวม Subdirectories (Recursive)
  • FileInfo.Length: ขนาดไฟล์เป็น Bytes (long)

ตัวอย่าง 1: ดึงไฟล์ทั้งหมด (รวม Subfolders)

using System;
using System.IO;

static void Main()
{
    string rootPath = @"C:\TestFolder";
    
    // *.* = ทุกไฟล์, AllDirectories = รวม Subfolders
    string[] files = Directory.GetFiles(rootPath, "*.*", SearchOption.AllDirectories);
    
    foreach (string file in files)
    {
        Console.WriteLine(file);
    }
}

ตัวอย่าง 2: ดึงเฉพาะโฟลเดอร์บนสุด

string[] files = Directory.GetFiles(rootPath, "*.*", SearchOption.TopDirectoryOnly);

ตัวอย่าง 3: ดึงไฟล์พร้อมขนาด (Bytes, KB, MB)

static void Main()
{
    string rootPath = @"C:\TestFolder";
    string[] files = Directory.GetFiles(rootPath, "*.*", SearchOption.AllDirectories);
    
    foreach (string file in files)
    {
        var info = new FileInfo(file);
        long bytes = info.Length;
        double kb = bytes / 1024.0;
        double mb = kb / 1024.0;
        double gb = mb / 1024.0;
        
        string sizeStr = bytes < 1024 ? $"{bytes} B"
                        : kb < 1024 ? $"{kb:F2} KB"
                        : mb < 1024 ? $"{mb:F2} MB"
                        : $"{gb:F2} GB";
        
        Console.WriteLine($"{Path.GetFileName(file)}: {sizeStr} ({bytes:N0} bytes)");
    }
}

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

document.pdf: 1.25 MB (1,310,720 bytes)
image.png: 512.50 KB (524,800 bytes)
notes.txt: 2.10 KB (2,150 bytes)
data.csv: 0 B (0 bytes)

ตัวอย่าง 4: ใช้ LINQ จัดกลุ่ม/กรอง

var largeFiles = Directory.GetFiles(rootPath, "*.*", SearchOption.AllDirectories)
    .Select(f => new FileInfo(f))
    .Where(fi => fi.Length > 10 * 1024 * 1024) // > 10 MB
    .OrderByDescending(fi => fi.Length)
    .Select(fi => new { fi.Name, SizeMB = fi.Length / (1024.0 * 1024.0) });

foreach (var f in largeFiles)
    Console.WriteLine($"{f.Name}: {f.SizeMB:F2} MB");

ข้อควรระวัง

  • UnauthorizedAccessException: อาจเกิดขึ้นหากไม่มีสิทธิ์เข้าถึงโฟลเดอร์ → ใช้ try-catch
  • PathTooLongException: Path ยาวเกิน 260 ตัวอักษร → ใช้ \\?\ Prefix หรือ .NET Core 3.0+ รองรับ Long Paths อัตโนมัติ
  • ประสิทธิภาพ: GetFiles โหลด Array ทั้งหมดใน Memory → โฟลเดอร์ใหญ่มากควรใช้ EnumerateFiles (Lazy)

EnumerateFiles (Memory Efficient)

// คืน IEnumerable - Lazy Evaluation
foreach (string file in Directory.EnumerateFiles(rootPath, "*.*", SearchOption.AllDirectories))
{
    // Process ทีละไฟล์ ไม่โหลดทั้งหมดใน Memory
}