Get Matching Files - CSharp File IO

CSharp examples for File IO:File Command

Description

Get Matching Files

Demo Code


using System.IO;/*from  w  w  w .j  a v  a 2s  . com*/
using System.Collections.Generic;

public class Main{
        public static IEnumerable<string> GetMatchingFiles(string rootDirPath, string fileSearchPattern)
        {
            var pending = new Queue<string>();
            pending.Enqueue(rootDirPath);
            string[] paths; 

            while (pending.Count > 0)
            {
                rootDirPath = pending.Dequeue();
                paths = Directory.GetFiles(rootDirPath, fileSearchPattern);
                foreach (var filePath in paths) {
                    yield return filePath;
                }
                paths = Directory.GetDirectories(rootDirPath);
                foreach (var dirPath in paths)
                {
                    var dirAttrs = File.GetAttributes(dirPath);
                    var isRecurseSymLink = (dirAttrs & FileAttributes.ReparsePoint) == FileAttributes.ReparsePoint;

                    if (!isRecurseSymLink)
                    {
                        pending.Enqueue(dirPath);
                    }
                }
            }
        }
        public static IEnumerable<string> GetMatchingFiles(this DirectoryInfo rootDirPath, string fileSearchPattern)
        {
            return GetMatchingFiles(rootDirPath.FullName, fileSearchPattern);
        }
}

Related Tutorials