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

前端 未结 8 1943
余生分开走
余生分开走 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 05:06

    You will have to do the recursion manually; don't use AllDirectories - look one folder at a time, then try getting the files from sub-dirs. Untested, but something like below (note uses a delegate rather than building an array):

    using System;
    using System.IO;
    static class Program
    {
        static void Main()
        {
            string path = ""; // TODO
            ApplyAllFiles(path, ProcessFile);
        }
        static void ProcessFile(string path) {/* ... */}
        static void ApplyAllFiles(string folder, Action fileAction)
        {
            foreach (string file in Directory.GetFiles(folder))
            {
                fileAction(file);
            }
            foreach (string subDir in Directory.GetDirectories(folder))
            {
                try
                {
                    ApplyAllFiles(subDir, fileAction);
                }
                catch
                {
                    // swallow, log, whatever
                }
            }
        }
    }
    

提交回复
热议问题