How to run programs without a specific path

0

Example: I want to automatically do a search of the program I write, and if you find an ".exe" application it will run it, if it does not find it, send a message saying that the program is not installed on your computer.

Process.Start(Programa + ".exe");

I wanted to know if there's any way to do it, because I searched a lot and did not find it.

    
asked by anonymous 04.09.2017 / 04:30

1 answer

2

If you are trying to run an application whose location is not determined, try searching for it recursively using a root directory.

Thus, the GetFiles method will enumerate all executable files recursively in all folders in the root directory:

References:

using System.IO;

Code:

string ProcurarOArquivo(string nome, string root) {
     // nome  -> nome do arquivo que esta sendo procurado
     // root  -> pasta raiz
     string[] Arquivos = Directory.GetFiles(root, "*.exe", SearchOption.AllDirectories);
     foreach(string a in Arquivos) {
          string A = Path.GetFileNameWithoutExtension(a);
          if(A.ToLower() == nome.ToLower()) return a;
          // A    -> arquivo com nome cortado
          // a    -> arquivo com nome e caminho completo
     }
     return "";
}

And to use, call the ProcurarOArquivo() method as in the example below:

// no exemplo abaixo, PastaParaProcurar é o diretório onde
// o aplicativo está sendo executado. Você pode alterar por
// qualquer diretório literal ou variável.
string PastaParaProcurar = Path.GetDirectoryName(System.Reflection.Assembly.GetEntryAssembly().Location);
// enfim chama o arquivo executável.
Process.Start(ProcurarOArquivo(Programa, PastaParaProcurar));
  

Notes:

     
  • If the file is not found, an empty%% will be returned.
  •   
  • If you want to search the entire system, set String to "C:\" , but the processor and memory usage will be arbitrarily large.
  •   
    
04.09.2017 / 08:13