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

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

    This should answer the question. I've ignored the issue of going through subdirectories, I'm assuming you have that figured out.

    Of course, you don't need to have a seperate method for this, but you might find it a useful place to also verify the path is valid, and deal with the other exceptions that you could encounter when calling GetFiles().

    Hope this helps.

    private string[] GetFiles(string path)
    {
        string[] files = null;
        try
        {
           files = Directory.GetFiles(path);
        }
        catch (UnauthorizedAccessException)
        {
           // might be nice to log this, or something ...
        }
    
        return files;
    }
    
    private void Processor(string path, bool recursive)
    {
        // leaving the recursive directory navigation out.
        string[] files = this.GetFiles(path);
        if (null != files)
        {
            foreach (string file in files)
            {
               this.Process(file);
            }
        }
        else
        {
           // again, might want to do something when you can't access the path?
        }
    }
    

提交回复
热议问题