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

เมธอด EnumerateFiles ใน C#

เมธอด Directory.EnumerateFiles() คืน IEnumerable<string> ของพาธไฟล์ ทำงานแบบ Lazy (Streaming) ไม่โหลดทั้งหมดเข้าหน่วยความจำ เหมาะสำหรับโฟลเดอร์ที่มีไฟล์เยอะมาก

พารามิเตอร์

  • Path - พาธโฟลเดอร์
  • SearchPattern - รูปแบบชื่อไฟล์ (เช่น "*.*", "*.txt")
  • SearchOption - AllDirectories (รวมโฟลเดอร์ย่อย) หรือ TopDirectoryOnly

ตัวอย่างโค้ด

using System;
using System.IO;

namespace Demo
{
    class Program
    {
        static void Main(string[] args)
        {
            foreach (string allFiles in Directory.EnumerateFiles(@"D:\NEW", "*.*", SearchOption.AllDirectories))
            {
                Console.WriteLine(allFiles);
            }
        }
    }
}

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

D:\NEW\my.txt
D:\NEW\amit.html
D:\NEW\tutorials\java\a.java

ข้อดีเหนือ GetFiles: เริ่มคืนค่าทันที ไม่ต้องรอสแกนเสร็จทั้งโฟลเดอร์ ประหยัดหน่วยความจำ