迭代注册表项

正如这里建议的那样,我需要遍历条目

HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\ 

找出我的应用程序的安装路径。 如何迭代,以便我可以找到给定DisplayNameInstallLocation值。 如何在C#中高效地完成它。

以下是实现目标的代码:

 class Program { static void Main(string[] args) { RegistryKey key = Registry.LocalMachine.OpenSubKey("Software\\Microsoft\\Windows\\CurrentVersion\\Uninstall"); foreach (var v in key.GetSubKeyNames()) { Console.WriteLine(v); RegistryKey productKey = key.OpenSubKey(v); if (productKey != null) { foreach (var value in productKey.GetValueNames()) { Console.WriteLine("\tValue:" + value); // Check for the publisher to ensure it's our product string keyValue = Convert.ToString(productKey.GetValue("Publisher")); if (!keyValue.Equals("MyPublisherCompanyName", StringComparison.OrdinalIgnoreCase)) continue; string productName = Convert.ToString(productKey.GetValue("DisplayName")); if (!productName.Equals("MyProductName", StringComparison.OrdinalIgnoreCase)) return; string uninstallPath = Convert.ToString(productKey.GetValue("InstallSource")); // Do something with this valuable information } } } Console.ReadLine(); } } 

编辑:有关查找应用程序安装路径的更全面方法,请参阅此方法 ,它演示了注释中建议的using处置。 https://stackoverflow.com/a/26686738/495455

 using (RegistryKey key = Registry.LocalMachine.OpenSubKey(@"Whater\The\Key")) { if (key != null) { foreach (string ValueOfName in key.GetValueNames()) { try { bool Value = bool.Parse((string)key.GetValue(ValueOfName)); } catch (Exception ex) {} } } } 

使用bool强制转换:D – 所以字符串应该是True或False。

对于用户注册表配置单元,请使用Registry.CurrentUser而不是Registry.LocalMachine