获取文件递归:跳过无法读取的文件/目录?(Getting files recursively: sk

2019-06-26 23:50发布

我想所有目录中的文件的一个数组(包括子文件夹中的文件)

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

这样做的问题是:如果抛出一个异常,整个命令停止。 有没有更好的办法做到这一点,这样,如果一个文件夹不能访问它只是跳过它?

Answer 1:

你可能不得不多做一点打字自己,那么,写一个目录步行者像这样的:

    public static string[] FindAllFiles(string rootDir) {
        var pathsToSearch = new Queue<string>();
        var foundFiles = new List<string>();

        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();
    }


Answer 2:

试试这个 :

DirectoryInfo directory = new DirectoryInfo(@"c:\");
        DirectoryInfo[] folders = directory.GetDirectories("*", SearchOption.AllDirectories);

        List<string> files = new List<string>();
        foreach (DirectoryInfo info in folders)
        {
            foreach (FileInfo file in info.GetFiles())
            {
                files.Add(file.Name);
            }
        }


Answer 3:

或者试试这个:

        DirectoryInfo dirs = new DirectoryInfo(@"c:\");
        List<string> filenames = (from i in dirs.GetFiles("*", SearchOption.AllDirectories)
                                  select i.Name).ToList();

或文件不带扩展名:

        DirectoryInfo dirs = new DirectoryInfo@"c:\");
        List<string> filenames = (from i in dirs.GetFiles("*", SearchOption.AllDirectories)
                                  select System.IO.Path.GetFileNameWithoutExtension(i.Name)).ToList();


文章来源: Getting files recursively: skip files/directories that cannot be read?