-->

How to skip folders with unauthorized access while

2019-02-26 07:26发布

问题:

This question already has an answer here:

  • Getting files recursively: skip files/directories that cannot be read? 3 answers
  • UnauthorizedAccessException cannot resolve Directory.GetFiles failure [duplicate] 7 answers

I have this for finding files and listing to list .but when it comes to a folder that needs authorized access, it stops. How can I make this skip those folders and carry on?

string[] filetypes = new string[] { "3gp", "avi", "dat", "mp4", "wmv", 
                                                         "mov", "mpg", "flv",  }
try
{
    foreach (string ft in filetypes)
    {                    
        files.AddRange(dif.GetFiles(string.Format("*.{0}", ft),
                                                  SearchOption.AllDirectories));    
    }
}
catch
{
}

回答1:

static void GetFiles(string dir)
{
    string[] filetypes = new string[] { "3gp", "avi", "dat", "mp4", "wmv", 
                                                     "mov", "mpg", "flv",  }
    foreach(string ft in filetypes)
    {
       foreach (string file in Directory.GetFiles(dir, string.Format("*.{0}", ft),
                                              SearchOption.TopDirectoryOnly)))
       { 
             files.Add(new FileInfo(file));
       }
    }
    foreach (string subDir in Directory.GetDirectories(dir))
    {
        try
        {
            GetFiles(subDir);
        }
        catch
        {
        }
    }
}

Do it using recursion not AllDirectories

run it like GetFiles(dif)



标签: c# getfiles