C# 遍历注册表项
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1458653/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Iterate through registry entries
提问by Nemo
As suggested here, I need to iterate through entries in
正如这里所建议的,我需要遍历中的条目
HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\
to find out the installed path of my application. How to iterate so that I can find out the InstallLocationvalue given the DisplayName. How to do it efficiently in C#.
找出我的应用程序的安装路径。如何迭代以便我可以找出给定DisplayName的 InstallLocation值。如何在 C# 中有效地做到这一点。
采纳答案by Mike J
Below is code to achieve your goal:
以下是实现目标的代码:
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();
}
}
Edit:See this method for a more comprehensive way to find an Applications Install Path, it demonstrates the using
disposing as suggested in the comments.
https://stackoverflow.com/a/26686738/495455
编辑:有关查找 Applications Install Path 的更全面方法,请参阅此方法,它演示using
了评论中建议的处置。
https://stackoverflow.com/a/26686738/495455
回答by rémy
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) {}
}
}
}
With a bool cast :D - so the string is expected to be True or False.
使用 bool cast :D - 所以字符串应该是 True 或 False。
For the user registry hive use Registry.CurrentUserinstead of Registry.LocalMachine
对于用户注册表配置单元使用Registry.CurrentUser而不是 Registry.LocalMachine