我正在编写需要检查程序是否已安装的代码,如果是,请获取路径。路径存储在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);
答案 0 :(得分:1)
我通过将我的代码重构为更清晰,更符合逻辑的东西来解决这个问题。
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;
}
}