Ignore folders/files when Directory.GetFiles() is denied access

前端 未结 8 1962
余生分开走
余生分开走 2020-11-22 04:27

I am trying to display a list of all files found in the selected directory (and optionally any subdirectories). The problem I am having is that when the GetFiles() method co

8条回答
  •  清歌不尽
    2020-11-22 04:52

    A simple way to do this is by using a List for files and a Queue for directories. It conserves memory. If you use a recursive program to do the same task, that could throw OutOfMemory exception. The output: files added in the List, are organised according to the top to bottom (breadth first) directory tree.

    public static List GetAllFilesFromFolder(string root, bool searchSubfolders) {
        Queue folders = new Queue();
        List files = new List();
        folders.Enqueue(root);
        while (folders.Count != 0) {
            string currentFolder = folders.Dequeue();
            try {
                string[] filesInCurrent = System.IO.Directory.GetFiles(currentFolder, "*.*", System.IO.SearchOption.TopDirectoryOnly);
                files.AddRange(filesInCurrent);
            }
            catch {
                // Do Nothing
            }
            try {
                if (searchSubfolders) {
                    string[] foldersInCurrent = System.IO.Directory.GetDirectories(currentFolder, "*.*", System.IO.SearchOption.TopDirectoryOnly);
                    foreach (string _current in foldersInCurrent) {
                        folders.Enqueue(_current);
                    }
                }
            }
            catch {
                // Do Nothing
            }
        }
        return files;
    }
    

    Steps:

    1. Enqueue the root in the queue
    2. In a loop, Dequeue it, Add the files in that directory to the list, and Add the subfolders to the queue.
    3. Repeat untill the queue is empty.

提交回复
热议问题