我正在编写代码,需要检查是否安装了程序,如果安装了,则获取路径。路径存储在任一
HKEY_LOCAL_MACHINE\SOFTWARE\Some\Registry\Path\InstallLocation
或
HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\Some\Registry\Path\InstallLocation
取决于安装的是 32 位还是 64 位版本的程序。
我现在的代码在 64 位机器上运行时无法找到 32 位安装的路径:
const string topKeyPath = @"HKEY_LOCAL_MACHINE\SOFTWARE";
const string subLocationPath = @"Some\Registry\Path\InstallLocation";
object pathObj = Registry.GetValue(topKeyPath + @"\" + subLocationPath, null, null);
if (pathObj == null) // if 32-bit isn't installed, try to find 64-bit
{
try
{
RegistryKey view32 = RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, RegistryView.Registry32);
view32 = view32.OpenSubKey("SOFTWARE");
view32 = view32.OpenSubKey(subLocationPath);
pathObj = view32.OpenSubKey(subLocationPath, false).GetValue(null);
if (pathObj == null)
{
throw new InvalidOperationException("Not installed.");
}
}
catch (Exception e)
{
throw new InvalidOperationException("Not installed.", e);
}
}
string installPath = Convert.ToString(pathObj);
我通过将代码重构为更干净、更逻辑的方式解决了这个问题。
string installPath = GetInstallLocation(RegistryView.Default); // try matching architecture
if (installPath == null)
{
installPath = GetInstallLocation(RegistryView.Registry64); // explicitly try for 64-bit
}
if (installPath == null)
{
installPath = GetInstallLocation(RegistryView.Registry32); // explicitly try for 32-bit
}
if (installPath == null) // must not be installed
{
throw new InvalidOperationException("Program is not instlaled.");
}
public static string GetInstallLocation(RegistryView flavor)
{
const string subLocationPath = @"SOFTWARE\Microsoft\Some\Registry\Path\InstallLocation";
object pathObj;
try
{
RegistryKey view32 = RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, flavor);
view32 = view32.OpenSubKey(subLocationPath);
pathObj = view32.GetValue(null);
return pathObj != null ? Convert.ToString(pathObj) : null;
}
catch (Exception)
{
return null;
}
}