Search for files by extension

5

In a Windows Forms application I would like to know how to fetch all files that exist and contain the word teste in the file extension. For example, opening a folder in Windows and typing *.teste* into the search field will return all files that contain that word in its extension regardless of whether it is .teste1 , .teste2 ...

 string Diretorio = @"C:\teste\";
 string Arquivo = Diretorio + Codigo.Trim() + "E" + "\" + Data;

 if (File.Exists(Arquivo + ".teste"))
 {
     Retorno = true;
 }

In the code snippet above, the word teste was set to a file extension. However if I have the file with the extension .teste1 or .teste2 the file will no longer be found.

    
asked by anonymous 04.05.2018 / 19:54

2 answers

6

You can get all files in the directory and see if the extensions contain what you want:

DirectoryInfo directoryInfo = new DirectoryInfo(@"C:\teste\");

bool retorno;

string nomeArquivo = "MyFile";

int count = 0;
foreach (FileInfo file in directoryInfo.GetFiles())
{
    if (file.Name == nomeArquivo && file.Extension.Contains(".ok"))
        retorno = true;
}

In this other option below it is checked if there is any file with that name and that it contains in the extension the word "ok", if it exists, count will return greater than 0 and the return variable will be equal true / p>

bool retorno = directoryInfo.GetFiles().Where(p => p.Extension.Contains(".ok") && p.Name == nomeArquivo).ToList().Count > 0; 
    
04.05.2018 / 20:06
2

Just complementing @Barbetta's answer, which is correct. There is one however in the directory to have thousands of files, in which case the runtime can be considerable, especially if we are looking at a network drive.

A faster / cleaner way to get this information would be to use a searchPattern (the same pattern we use when looking for files in Windows).

Practical example for your specific case:

string[] files = System.IO.Directory.GetFiles(@"C:\Diretorio\", "nomedoarquivo.ok*");
// Para saber a quantidade use a propriedade do array .Length
// int quantidade = files.Length;

For more information, consult the official documentation (which has a few more examples and explains some parts if you ever want to use a * .xls type filter).

Link: link

    
05.05.2018 / 05:26