How to find a file that cannot be fully qualified using the environment path?

I have an executable name like "cmd.exe" and you need to solve its fully qualified path. I know 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 must be a better way, right?

+3
source share
5 answers

- , PATH - , Windows , .

+2

:

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

: C:\WINDOWS\system32

Path.Combine() , . , File.Exists().

+4

Linq

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

?

Dan

+3

, ; , , .

    static class Win32
    {
        [DllImport("shlwapi.dll", CharSet = CharSet.Auto, SetLastError = false)]
        static extern bool PathFindOnPath([MarshalAs(UnmanagedType.LPTStr)] StringBuilder pszFile, IntPtr unused);

        public static bool FindInPath(String pszFile, out String fullPath)
        {
            const int MAX_PATH = 260;
            StringBuilder sb = new StringBuilder(pszFile, MAX_PATH);
            bool found = PathFindOnPath(sb, IntPtr.Zero);
            fullPath = found ? sb.ToString() : null;
            return found;
        }
    }
+1

You can do this from the command line using PowerShell . If you want to start the process with C # and analyze its result, you can use this approach. I do not think this is easier than what you are already doing.

0
source

Source: https://habr.com/ru/post/1717764/


All Articles