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

时间:2011-09-17 00:40:26

标签: c#

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

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

4 个答案:

答案 0 :(得分:5)

我找到this question,它指示我this article。 为了便于阅读,我修改了源代码,并专门解决了你的问题(请注意,我已经猜到了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();
}

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

请记住,此方法会返回第一个匹配路径,因此请不要为它提供过于通用的appName参数(例如“Microsoft”)或者您可能赢了“得到你想要的东西。

答案 1 :(得分:1)

好吧,如果您正在尝试查看某个程序是否存在您正在寻找的程序(例如BeyondCompare.exe),您只需使用以下呼叫:

System.IO.File.Exists("path_to_program.exe");

如果它返回true,那么您知道您的程序存在,您可以使用您的流程转轮代码运行它。如果它返回false,那么你知道它不存在,你不应该启动你的过程。

如果我误解了你的问题,请告诉我,我会相应更新我的答案。

感谢。希望这有帮助!

答案 2 :(得分:1)

为此做的简单逻辑。

string filepath = "c:\windows\test.exe";
bool bOk = false;
try
{
  bOk = System.IO.File.Exists(filepath);
}
catch (Exception ex)
{
      Console.WriteLine(ex.Message);
 }
if (!bOk)
{
    Console.WriteLine("Error: Invalid Path");
}
else
{
   Process p = new Process();
    p.StartInfo.FileName = filepath;
    p.StartInfo.Arguments = "/c dir *.cs";
    p.StartInfo.UseShellExecute = false;
    p.StartInfo.RedirectStandardOutput = true;
    p.Start();

    string output = p.StandardOutput.ReadToEnd();
    p.WaitForExit();

    Console.WriteLine("Output:");
    Console.WriteLine(output);    
}

答案 3 :(得分:0)

您确定不需要进行检查吗?只需启动没有路径的程序(只有文件名)并设置ProcessStartInfo.UseShellExecute = true

Windows将在其已安装的应用列表中查找该应用。如果找不到,Process.Start()将失败。有趣的是,您永远不必关心应用程序的存储位置。