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

前端 未结 8 1848
余生分开走
余生分开走 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:46

    This simple function works well and meets the questions requirements.

    private List GetFiles(string path, string pattern)
    {
        var files = new List();
        var directories = new string[] { };
    
        try
        {
            files.AddRange(Directory.GetFiles(path, pattern, SearchOption.TopDirectoryOnly));
            directories = Directory.GetDirectories(path);
        }
        catch (UnauthorizedAccessException) { }
    
        foreach (var directory in directories)
            try
            {
                files.AddRange(GetFiles(directory, pattern));
            }
            catch (UnauthorizedAccessException) { }
    
        return files;
    }
    

提交回复
热议问题