Searching and opening files by name

Asked

Viewed 85 times

-1

Well I’d like a code that looks all over the directory @"c:\" with a name I put and open the folder or folders where they are located.

Ex:

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

Note: even if I write the name capitalized or only a piece of the file name appears.

3 answers

1

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

The parameter searchPattern 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: searches folders and subfolders
  • Searchoption.Toponlydirectory: looks only in the parameter folder path.

In the example below, search for all files starting at 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 on Windows. C:\Pasta\Arquivo.exe refers to the same c:\pasta\arquivo.exe or C:\PASTA\ARQUIVO.EXE.

Either way it’s worth it read the documentation.

0

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

You just need to inform the folder where it will be perform the search in your case, C:\\ ;

The filter for searching, in your case the file name;

And the search option, in your case, AllDirectories to search in all subfolders.

Follows 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
}

0

Use Directoryinfo, depending on windows version you can do a full scan of your disk by searching with "C:\.*"

Browser other questions tagged

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