Check if an executable exists in the Windows path

后端 未结 8 1742
栀梦
栀梦 2020-11-29 06:39

If I run a process with ShellExecute (or in .net with System.Diagnostics.Process.Start()) the filename process to start doesn\'t need to be a full

8条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-11-29 06:52

    I tried out Dunc's "where" process and it works, but it's slow and resource-heavy and there's the slight danger of having an orphaned process.

    I like Eugene Mala's tip about PathFindOnPath, so I fleshed that out as a complete answer. This is what I'm using for our custom in-house tool.

    /// 
    /// Gets the full path of the given executable filename as if the user had entered this
    /// executable in a shell. So, for example, the Windows PATH environment variable will
    /// be examined. If the filename can't be found by Windows, null is returned.
    /// 
    /// The full path if successful, or null otherwise.
    public static string GetFullPathFromWindows(string exeName)
    {
        if (exeName.Length >= MAX_PATH)
            throw new ArgumentException($"The executable name '{exeName}' must have less than {MAX_PATH} characters.",
                nameof(exeName));
    
        StringBuilder sb = new StringBuilder(exeName, MAX_PATH);
        return PathFindOnPath(sb, null) ? sb.ToString() : null;
    }
    
    // https://docs.microsoft.com/en-us/windows/desktop/api/shlwapi/nf-shlwapi-pathfindonpathw
    // https://www.pinvoke.net/default.aspx/shlwapi.PathFindOnPath
    [DllImport("shlwapi.dll", CharSet = CharSet.Unicode, SetLastError = false)]
    static extern bool PathFindOnPath([In, Out] StringBuilder pszFile, [In] string[] ppszOtherDirs);
    
    // from MAPIWIN.h :
    private const int MAX_PATH = 260;
    

提交回复
热议问题