Is there a faster way than this to find all the files in a directory and all sub directories?

前端 未结 16 1421
盖世英雄少女心
盖世英雄少女心 2020-11-29 17:49

I\'m writing a program that needs to search a directory and all its sub directories for files that have a certain extension. This is going to be used both on a local, and a

16条回答
  •  暖寄归人
    2020-11-29 18:21

    Try this iterator block version that avoids recursion and the Info objects:

    public static IEnumerable GetFileList(string fileSearchPattern, string rootFolderPath)
    {
        Queue pending = new Queue();
        pending.Enqueue(rootFolderPath);
        string[] tmp;
        while (pending.Count > 0)
        {
            rootFolderPath = pending.Dequeue();
            try
            {
                tmp = Directory.GetFiles(rootFolderPath, fileSearchPattern);
            }
            catch (UnauthorizedAccessException)
            {
                continue;
            }
            for (int i = 0; i < tmp.Length; i++)
            {
                yield return tmp[i];
            }
            tmp = Directory.GetDirectories(rootFolderPath);
            for (int i = 0; i < tmp.Length; i++)
            {
                pending.Enqueue(tmp[i]);
            }
        }
    }
    

    Note also that 4.0 has inbuilt iterator block versions (EnumerateFiles, EnumerateFileSystemEntries) that may be faster (more direct access to the file system; less arrays)

提交回复
热议问题