Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I find a file that may not be fully-qualified by using the environment path?

I have an executable name, like "cmd.exe" and need to resolve it's fully-qualified path. I know the exe appears in one of the directories listed in the PATH environment variable. Is there a way to resolve the full path without parsing and testing each directory in the PATH variable? basically I don't want to do this:

foreach (string entry in Environment.GetEnvironmentVariable("PATH").Split(';'))
    ...

There has to be a better way, right?

like image 311
csharptest.net Avatar asked Sep 15 '09 21:09

csharptest.net


2 Answers

Here's another approach:

string exe = "cmd.exe";
string result = Environment.GetEnvironmentVariable("PATH")
    .Split(';')
    .Where(s => File.Exists(Path.Combine(s, exe)))
    .FirstOrDefault();

Result: C:\WINDOWS\system32

The Path.Combine() call is used to handle paths that don't end with a trailing slash. This will properly concatenate the strings to be used by the File.Exists() method.

like image 163
Ahmad Mageed Avatar answered Oct 02 '22 09:10

Ahmad Mageed


You could Linq it with

string path = Environment
                .GetEnvironmentVariable("PATH")
                .Split(';')
                .FirstOrDefault(p => File.Exists(p + filename));

A little more readable maybe?

Dan

like image 39
Daniel Elliott Avatar answered Oct 02 '22 08:10

Daniel Elliott