如何使用C#找出程序的路径

gee*_*eek 4 c#

我找到了一段代码,解释了如何使用System.Diagnostics.Process.StartC#运行外部程序。该代码段显示正在运行cmd.exe,位于路径中。

假设有一些外部程序(例如“超越比较”)。我不知道它是否已安装在PC上。如何检查是否使用C#安装了该程序?如果已安装该程序,我想找到路径以便启动它。

Rob*_*Rob 5

我发现了这个问题,这使我想到了本文。我已经修改了源代码以提高可读性,并专门解决了您的问题(请注意,我猜到了Beyond Compare的描述和可执行文件名称。)

您可以通过以下方式调用它main

string path = FindAppPath("Beyond Compare"); 
if (path == null)
{
    Console.WriteLine("Failed to find program path.");
    return;
}
path += "BeyondCompare.exe";
if (File.Exists(path))
{
    Process beyondCompare = new Process()
    {
        StartInfo = new ProcessStartInfo()
        {
            FileName = path + "BeyondCompare.exe",
            Arguments = string.Empty // You may need to specify args.
        }
    };
    beyondCompare.Start();
}
Run Code Online (Sandbox Code Playgroud)

来源FindAppPath如下:

static string FindAppPath(string appName)
{
    // If you don't use contracts, check this and throw ArgumentException
    Contract.Requires(!string.IsNullOrEmpty(appName));
    const string keyPath =
        @"SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall";

    using (RegistryKey key = Registry.LocalMachine.OpenSubKey(keyPath))
    {
        var installed = 
            (from skName in key.GetSubKeyNames()
            let subkey = key.OpenSubKey(skName)
            select new
            {
                name = subkey.GetValue("DisplayName") as string,
                path = subkey.GetValue("InstallLocation") as string

            }).ToList();

        var desired = installed.FindAll(
            program => program.name != null && 
            program.name.Contains(appName)  &&
            !String.IsNullOrEmpty(program.path));

        return (desired.Count > 0) ? desired[0].path : null;
    }
}
Run Code Online (Sandbox Code Playgroud)

请记住,此方法返回第一个匹配的路径,因此不要给它提供appName过于通用的参数(例如“ Microsoft”),否则您可能无法获得所需的内容。