cesq
cesq

Reputation: 355

Directory.Getfiles does not return any value when used with "SearchOption.AllDirectories"

Hi I am trying to search for all files and folders that start with a given sequence of characters in a specific path. (The path is given by the user and so is the sequence).

To accomplish this I have been using the Directory.GetFiles and Directory.GetDirectories methods. However when I search with no search option defined, it doesn't return all the files / folders that could've been found. So I added the SearchOption.AllDirectiories argument but when it's present, the function doesn't return anything. This is my code:

try
{
    // Search for directories 

    foreach (string d in Directory.GetDirectories(path, $"{param}*", SearchOption.AllDirectories))   
    {
        Console.WriteLine(d);
        found_directories.Add(d);
    }

    Console.WriteLine("");
    // Search for files

    foreach (string f in Directory.GetFiles(path, $"{param}*", SearchOption.AllDirectories))
    {
        Console.WriteLine(f);
        found_files.Add(f);
    }

}
catch (UnauthorizedAccessException)
{
    // Some directories cannot be accessed and hence cause the program to crash 
    // So it's neccesary to catch the error
}

break;

I have already looked at these posts (which didn't help me):

Directory.GetFiles Not returning a file

Directory.GetFiles(path, ".txt", SearchOption.AllDirectories); doesn't deliver a file

Directory.GetFiles - SearchOption.AllDirectories Does not give files in subfolders (vb)

Upvotes: 0

Views: 1350

Answers (1)

cesq
cesq

Reputation: 355

So after doing a little bit of research I found the issue.

  • Directory.GetFiles() / Directory.GetDirectories() are inherently flawed. When any exception occurs the function does not continue searching for files / folders. It's because there's no error handling inside these functions. Trying to write the try/catch yourself is non beneficial, since even when you catch an exception, the function will finish without returning anything.

Is there a solution?

No, but there's a workaround.

The workaround

Use this github repo instead: https://github.com/astrohart/FileSystemEnumerable/

It is an improved version of the function, it does all the error handling so you don't need to worry about anything, I tested it myself and it works for me.

The github repo is realated to this stackoverflow question.

For anyone that would maybe have the same problem in the future, I recommend you check out this link.

I hope that by answering my own question, I helped someone in the future. Cheers :)!

Upvotes: 1

Related Questions