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

前端 未结 2 1793
不思量自难忘°
不思量自难忘° 2021-01-19 22:22

I am using this code to search all directories in all drives to search for all .txt files:

public List Search()
{
    var files = new List

        
相关标签:
2条回答
  • 2021-01-19 22:34

    The problem here is that some files you don't have control on it to get access it's files. So you need to use try{ } catch{ }. But i think you can't handle this while processing the whole file system directories at once. SO you need to first get list of all directories then process each directory at once at while you are processing specific directory files you can handle that kind of exception.

    Kindly check this:

    unauthorizedaccessexception-cannot-resolve-directory-getfiles-failure

    0 讨论(0)
  • 2021-01-19 22:35

    This is simply a permissions problem. Use a try/catch block. Some of the folders on your disk including RecycleBin folders are not accessible to 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 Directory.GetFiles with AllDirectories option has an inherent problem that it will fail if ANY of the folders in the entire drive is not accessible, and thus you'll not get any files for that drive in your results. The solution is to do manual recursion. An excellent example of that approach is available in this SO question.

    0 讨论(0)
提交回复
热议问题