Getting files recursively: skip files/directories that cannot be read?

后端 未结 4 1461
感情败类
感情败类 2021-01-18 06:11

I want to get all of the files in a directory in an array (including the files in subfolders)

string[] filePaths = Directory.GetFiles(@\"c:\\\",SearchOption.         


        
4条回答
  •  死守一世寂寞
    2021-01-18 06:36

    You'd probably have to do a bit more typing yourself then, and write a directory walker like this one:

        public static string[] FindAllFiles(string rootDir) {
            var pathsToSearch = new Queue();
            var foundFiles = new List();
    
            pathsToSearch.Enqueue(rootDir);
    
            while (pathsToSearch.Count > 0) {
                var dir = pathsToSearch.Dequeue();
    
                try {
                    var files = Directory.GetFiles(dir);
                    foreach (var file in Directory.GetFiles(dir)) {
                        foundFiles.Add(file);
                    }
    
                    foreach (var subDir in Directory.GetDirectories(dir)) {
                        pathsToSearch.Enqueue(subDir);
                    }
    
                } catch (Exception /* TODO: catch correct exception */) {
                    // Swallow.  Gulp!
                }
            }
    
            return foundFiles.ToArray();
        }
    

提交回复
热议问题