How to fetch a file in all folders

Asked

Viewed 1,923 times

4

How to create an application that does a full search in a folder or disk looking for a file who in the image

Buscando...

I’ve tried to use
Directory.GetFiles and Directory.GetDirectory
But when it gets to a folder that you don’t have access to it cancels out all the action.

And even so there was no possibility to search a file by name, size or extension.

In the case of the above image it searches the entire disk for a file called aria2c.exe

And when this app finds this file, it starts right after the installation.

3 answers

3


If what you want is to dodge the directories you don’t have permission to, and keep looking in the directories you have permission to, you’ll have to recursively implement the search on your own, one directory at a time, and use try/catch around the calls Directory.GetFiles and Directory.GetDirectories.

public static IEnumerable<string> AcharArquivosComPermissaoRecursivamente(
    string caminhoRaiz,
    string padrao = "*.*")
{
    var caminhosPendentes = new Queue<string>();
    var arquivosAchados = new List<string>();

    caminhosPendentes.Enqueue(caminhoRaiz);

    while (caminhosPendentes.Count > 0)
    {
        var caminhoAtual = caminhosPendentes.Dequeue();

        try
        {
            var listaArquivos = Directory.GetFiles(caminhoAtual, padrao);
            arquivosAchados.AddRange(listaArquivos);

            foreach (var subDiretorio in Directory.GetDirectories(caminhoAtual))
                caminhosPendentes.Enqueue(subDiretorio);
        }
        catch (UnauthorizedAccessException)
        {
            // Ignorar exceções sobre acesso não autorizado.
        }
    }

    return arquivosAchados;
}

2

I believe your attempt, using Directory.GetDirectories() is the right start.

If you are knocking ahead with access exceptions, you will need to Permissions when you’re doing - for example, using the runas.exe.

2

Basically this is it:

var lista = new DirectoryInfo("c:\\").GetFiles("aria2c.exe", SearchOption.AllDirectories);

The secret is the second parameter of GetFiles() which determines the recursive search with the enumeration SearchOption.

If you want to handle access errors on your own and prevent the abort method can use a solution like the one below. Interestingly Marc Gravel who works at SE has already given several answers each in a different way, I found is the most suitable for you:

using static System.Console;
using System.IO;
using System.Collections.Generic;
                    
public class Program {
    public static void Main() {
        foreach (var file in FileUtil.GetFiles("c:\\", "aria2c.exe")) WriteLine(file);
    }
}

public static class FileUtil {
    public static IEnumerable<string> GetFiles(string root, string searchPattern) {
        var pending = new Stack<string>();
        pending.Push(root);
        while (pending.Count != 0) {
            var path = pending.Pop();
            string[] next = null;
            try {
                next = Directory.GetFiles(path, searchPattern);                    
            }
            catch { } //aqui você pode colocar log, aviso ou fazer algo útil se tiver problemas
            if (next != null && next.Length != 0) foreach (var file in next) yield return file;
            try {
                next = Directory.GetDirectories(path);
                foreach (var subdir in next) pending.Push(subdir);
            }
            catch { } //aqui você pode colocar log, aviso ou fazer algo útil se tiver problemas
        }
    }
}

Behold working in the ideone. And in the .NET Fiddle. Also put on the Github for future reference.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.