c#: 判断Firefox是否安装

时间:2022-08-04 18:05:54

1、源起:

KV项目需要给浏览器安装下载插件,就需要判断是否安装对应浏览器,发现判断卸载目录方法,32位程序在.net 2.0运行环境下,常规方法不能访问64位注册表位置,导致不能判断。

2、卸载键值

@"SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\"

@"SOFTWARE\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall\"

c#: 判断Firefox是否安装

所有安装过的程序,其若支持卸载,键值都在此处。

32位系统,以@"SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\"做为key值访问,其也只能定位到@"SOFTWARE\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall\"这里,不能直接访问64位值位。

因此,以下代码判断,对于64位系统,判断不到。也就是说,下面代码,直判断到Wow6432节点!

        private static string FirefoxInstallLoation()
{
const string unInsPath = @"SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\";
const string unInsPath64 = @"SOFTWARE\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall\"; string firefoxLocation = string.Empty;
try
{
//这里,32位程序,实际定位到的,是Wow6432下节点
var unInsKey = Registry.LocalMachine.OpenSubKey(unInsPath);
if (unInsKey == null)
return string.Empty; string[] unInsKeyNames = unInsKey.GetSubKeyNames();
foreach (var name in unInsKeyNames)
{
if (name.Contains("Mozilla Firefox"))
{
firefoxLocation = unInsKey.OpenSubKey(name).GetValue("InstallLocation", string.Empty).ToString();
if (Directory.Exists(firefoxLocation))
return firefoxLocation;
}
}

//它仍是定位到Wow6432下
unInsKey = Registry.LocalMachine.OpenSubKey(unInsPath64);
if (unInsKey == null)
return string.Empty; unInsKeyNames = unInsKey.GetSubKeyNames();
foreach (var name in unInsKeyNames)
{
if (name.Contains("Mozilla Firefox"))
{
firefoxLocation = unInsKey.OpenSubKey(name).GetValue("InstallLocation", string.Empty).ToString();
if (Directory.Exists(firefoxLocation))
return firefoxLocation;
}
}
}
catch
{
}
return firefoxLocation;
}

其始终定位到的,是此处:

c#: 判断Firefox是否安装

3、灵光乍现,App Paths

于是寻找其它方法,还操注册表的心,真给搜出来个东西:

c#: 判断Firefox是否安装

@"SOFTWARE\Microsoft\Windows\CurrentVersion\App Paths\firefox.exe"

此键值,在64、32位下都存在,其程序路径、安装路径都有了,看来找对了地方,写代码如下:

        //检测Chrome卸载程序判断其是否安装
private static bool CheckFirefoxInstalled()
{
return File.Exists(FirefoxInstallLoation());
} private static string FirefoxInstallLoation()
{
const string firefoxAppPath = @"SOFTWARE\Microsoft\Windows\CurrentVersion\App Paths\firefox.exe";
try
{
var firefoxKey = Registry.LocalMachine.OpenSubKey(firefoxAppPath);
if (firefoxKey == null)
return string.Empty;
return firefoxKey.GetValue(string.Empty).ToString();
}
catch
{
}
return string.Empty;
}

验证判断正常,问题解决!

4、参数设置判断效果

c#: 判断Firefox是否安装