Check if an executable exists in the Windows path

后端 未结 8 1744
栀梦
栀梦 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:51

    Ok, a better way I think...

    This uses the where command, which is available at least on Windows 7/Server 2003:

    public static bool ExistsOnPath(string exeName)
    {
        try
        {
            using (Process p = new Process())
            {
                p.StartInfo.UseShellExecute = false;
                p.StartInfo.FileName = "where";
                p.StartInfo.Arguments = exeName;
                p.Start();
                p.WaitForExit();
                return p.ExitCode == 0;
            }
        }
        catch(Win32Exception)
        {
            throw new Exception("'where' command is not on path");
        }
    }
    
    public static string GetFullPath(string exeName)
    {
        try
        {
            using (Process p = new Process())
            {
                p.StartInfo.UseShellExecute = false;
                p.StartInfo.FileName = "where";
                p.StartInfo.Arguments = exeName;
                p.StartInfo.RedirectStandardOutput = true;
                p.Start();
                string output = p.StandardOutput.ReadToEnd();
                p.WaitForExit();
    
                if (p.ExitCode != 0)
                    return null;
    
                // just return first match
                return output.Substring(0, output.IndexOf(Environment.NewLine));
            }
        }
        catch(Win32Exception)
        {
            throw new Exception("'where' command is not on path");
        }
    }
    

提交回复
热议问题