Searching and opening files by name

-1

I would like a code that searches the entire directory @"c:\" with a name that I put and opened the folder or folders where they are located.

Ex:

Process.Start(@"c:\" + PastaOndeEstaLocalizadoOArquivo);

Note: Even if I type the uppercase name or only a piece of the file name appears.

    
asked by anonymous 16.09.2017 / 03:33

3 answers

1

You can use Directory.GetFiles by passing the searchPattern parameter.

The searchPattern parameter is a string that supports wildcards * (zero or more characters in position) and ? (zero or one character in position).

In this overload you will need the parameter searchOption . It supports the values:

  • SearchOption.AllDirectories: Search in folders and subfolders
  • SearchOption.TopOnlyDirectory: searches only the folder of the path parameter.

In the example below, search for all files that begin on a given term.

DirectoryInfo diretorioRaiz = new DirectoryInfo(@"C:\");
string termoPesquisa = "teste";
FileInfo[] arquivosEncontrados = diretorioRaiz.GetFiles($"*${termoPesquisa}*.*", 
           SearchOption.AllDirectories) // veja o wildcard e a extensão

// agora você tem a lista com os arquivos, manipule-os da maneira que preferir

Files and folders are case sensitive in Windows. C:\Pasta\Arquivo.exe refers to the same as c:\pasta\arquivo.exe or C:\PASTA\ARQUIVO.EXE .

Anyway it's worth read the documentation .

    
16.09.2017 / 05:10
0

Use DirectoryInfo, depending on the version of windows you can do a complete scan of your disk by doing the search with "C: \. *"

    
16.09.2017 / 06:41
0

You can use the GetFiles method of class Directory , which returns an array of strings with the name of each file found.

You just need to tell the folder where the search will be done, in your case, C:\ ;

The search filter, in its case the file name;

And the search option, in your case, AllDirectories to search in all sub-folders.

Follow the code:

string arquivo = "arquivo.txt";

string[] files = Directory.GetFiles("C:\", arquivo, SearchOption.AllDirectories);

foreach (string file in files)
{
    Process.Start(file); //abre o arquivo
    Process.Start(new FileInfo(file).DirectoryName);//abre a pasta do arquivo
}
    
16.09.2017 / 04:22