How to search all directories in all drives for .txt files?

I use this code to search all directories in all drives to search all .txt files:

public List<string> Search() { var files = new List<string>(); foreach (DriveInfo d in DriveInfo.GetDrives().Where(x => x.IsReady == true)) { files.AddRange(Directory.GetFiles(d.RootDirectory.FullName, "*.txt", SearchOption.AllDirectories)); } return files; } 

but at runtime I get this error: enter image description here

How to solve it?

Thanks.

+4
source share
2 answers

This is just a permissions issue. Use a try / catch block. Some of the folders on your drive, including the RecycleBin folders, are not available for unprivileged code.

 public List<string> Search() { var files = new List<string>(); foreach (DriveInfo d in DriveInfo.GetDrives().Where(x => x.IsReady)) { try { files.AddRange(Directory.GetFiles(d.RootDirectory.FullName, "*.txt", SearchOption.AllDirectories)); } catch(Exception e) { Logger.Log(e.Message); // Log it and move on } } return files; } 

Also note that using the Directory.GetFiles option with the AllDirectories parameter has an inherent problem, which will fail if ANY of the folders on the entire drive is inaccessible, and therefore you will not receive any files for this drive in your Results. The solution is to do manual recursion. A great example of this approach is this SO question .

+7
source

The problem here is that some files that you do not have control over access the files. Therefore, you need to use try{ } catch{ } . But I think you cannot handle this while processing all the file system directories at the same time. So, you need to first get a list of all directories, and then process each directory at once, while you are processing files of specific directories that can handle such an exception.

Please check this:

unauthorizedaccessexception-cannot-resolve-directory-getfiles-failure

0
source

Source: https://habr.com/ru/post/1491093/


All Articles