簡體   English   中英

如何使用環境路徑查找可能未完全限定的文件?

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

我有一個可執行名稱,例如“cmd.exe”,需要解析它的完全限定路徑。 我知道 exe 出現在 PATH 環境變量中列出的目錄之一中。 有沒有辦法在不解析和測試 PATH 變量中的每個目錄的情況下解析完整路徑? 基本上我不想這樣做:

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

必須有更好的方法,對吧?

這是另一種方法:

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() 方法要使用的字符串。

你可以用 Linq

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

也許更具可讀性?

好吧,我確實找到了以下內容; 但是,我想我會堅持托管實施。

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

這似乎已經是一種很好的方法了——據我所知,搜索PATH環境變量中的目錄是 Windows 在嘗試解析路徑時所做的事情。

我最終寫了這個函數:

private static string GetExecutablePath(string executableFileName)
{
    var path = Environment
        .GetEnvironmentVariable("PATH")!
        .Split(';')
        .Select(s => Path.Combine(s, executableFileName))
        .FirstOrDefault(x => File.Exists(x));
    if (path == null)
    {
        throw new Exception($"Cannot find {executableFileName}. Is it installed on your computer?");
    }
    return path;
}

就我而言,我想找到python.exe的路徑,所以我這樣調用函數:

GetExecutablePath("python.exe")

在我的情況下返回:

"C:\\Program Files\\Python39\\python.exe"

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM