How to run programs without specific path

Asked

Viewed 398 times

0

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

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

I wanted to know if there was a way, because I looked hard and I couldn’t find.

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 method GetFiles will enumerate all executable files recursively in all folders of the directory root:

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 method ProcurarOArquivo() 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));

Remarks:

  • If the file is not found, a String empty.
  • If you want to search the entire system, put "C:\" in PastaParaProcurar, but the use of processor and memory will be arbitrarily large.

Browser other questions tagged

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