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

我怕爱的太早我们不能终老 提交于 2019-11-30 17:29:34

问题


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?


回答1:


This seems like a pretty good way of doing it already -- as far as I know, searching through the directories in the PATH environment variable is what Windows does anyway when it's trying to resolve a path.




回答2:


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.




回答3:


You could Linq it with

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

A little more readable maybe?

Dan




回答4:


Well, I did find the following; however, I think I'll stick to the managed implementation.

    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;
        }
    }


来源:https://stackoverflow.com/questions/1429633/how-do-i-find-a-file-that-may-not-be-fully-qualified-by-using-the-environment-pa

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!