查找任何给定exe文件名的路径

时间:2019-03-19 01:41:55

标签: c#

我知道之前也曾问过类似的问题,但是所有答案都是不完整的,例如建议我使用AssocQueryString。但是,我仍然无法找到某些exe。例如,下面的代码无法找到outlook.exe或firefox.exe-在Windows资源管理器地址栏中键入outlook.exe会发现这些内容几乎是即时的。

在exe fileName下面的代码中,它可以是用户计算机上的任何本地位置,它可以位于或可以不位于用户搜索路径上。

如何改善此功能以查找文件? (这是从32位exe调用的)

// for example, get actual full path to outlook.exe
string fullPath = FindPath("outlook.exe");

public static string FindPath(string fileName)
{
    uint length = UnsafeMethods.MAX_PATH;
    StringBuilder path = new StringBuilder((int)length);

    if (Path.GetDirectoryName(fileName) == string.Empty)
    {
        if (UnsafeMethods.AssocQueryString(UnsafeMethods.AssocF.OpenByExeName, UnsafeMethods.AssocStr.Executable, fileName, null, path, ref length) != 0)
        {
            IntPtr filePart = IntPtr.Zero;
            IntPtr wow64Value = IntPtr.Zero;

            // try 64 bit path
            UnsafeMethods.Wow64DisableWow64FsRedirection(ref wow64Value);
            bool success = UnsafeMethods.SearchPath(null, fileName, null, path.Capacity, path, ref filePart) > 0;
            UnsafeMethods.Wow64RevertWow64FsRedirection(wow64Value);

            if (!success)
            {
                // try 32 bit path
                success = UnsafeMethods.SearchPath(null, fileName, null, path.Capacity, path, ref filePart) > 0;
            }
        }

        return path.ToString();
    }
    else
    {
        return fileName;
    }
}

1 个答案:

答案 0 :(得分:0)

似乎可以找到很多地方来找到exe的路径。尽管上面的原始代码有效,但这并不是详尽的搜索,您还需要查看注册表项SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\App Paths\\并检查SpecialFolders WindowsSystemSystemX86https://docs.microsoft.com/en-us/dotnet/api/system.environment.specialfolder?view=netframework-4.7.2