有没有人能给我解释一下我做错了什么,为什么这个不起作用?我只是尝试从注册表项中获取值,并将它们作为字典返回给main函数。
public Dictionary<string, string> ListPrograms()
{
///List<object> Apps = new List<object>();
Dictionary<string, string> Apps = new Dictionary<string, string>();
string registryKey = "SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Uninstall";
using (Microsoft.Win32.RegistryKey key = Registry.LocalMachine.OpenSubKey(registryKey))
{
(from a in key.GetSubKeyNames()
let r = key.OpenSubKey(a)
select new
{
DisplayName = r.GetValue("DisplayName"),
RegistryKey = r.GetValue("UninstallString")
})
.Distinct()
.OrderBy(c => c.DisplayName)
.Where(c => c.DisplayName != null && c.RegistryKey != null)
.ToDictionary(k => k.RegistryKey.ToString(), v => v.DisplayName.ToString());
}
return Apps;
}在检索字典之后,我将它绑定到一个列表框。
listBox1.DisplayMember = "Value";
listBox1.ValueMember = "Key";
listBox1.DataSource = new BindingSource(u.ListPrograms(), null);有没有更有效的方法来做到这一点?
发布于 2013-06-05 20:41:34
你的代码
In Line (from a in key.GetSubKeyNames()
将其更改为
Apps = (from a in key.GetSubKeyNames()
let r = key.OpenSubKey(a)
select new
{
DisplayName = r.GetValue("DisplayName"),
RegistryKey = r.GetValue("UninstallString")
})
.Distinct()
.OrderBy(c => c.DisplayName)
.Where(c => c.DisplayName != null && c.RegistryKey != null)
.ToDictionary(k => k.RegistryKey.ToString(), v => v.DisplayName.ToString());更新
下面是可用的代码
public static Dictionary<string, string> ListPrograms()
{
Dictionary<string, string> Apps = new Dictionary<string, string>();
string registryKey = "SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Uninstall";
using (Microsoft.Win32.RegistryKey key = Registry.LocalMachine.OpenSubKey(registryKey))
{
if (key != null)
{
var key1 = key.GetSubKeyNames();
foreach (var z in key1.Select(s => key.OpenSubKey(s))
.Where(b => b != null && b.GetValue("DisplayName") != null && b.GetValue("UninstallString") != null).Select(b => new
{
DisplayName = b.GetValue("DisplayName").ToString(),
RegistryKey = b.GetValue("UninstallString").ToString()
}).Where(z => !Apps.ContainsKey(z.RegistryKey)))
{
Apps.Add(z.RegistryKey, z.DisplayName);
}
}
}
return Apps;
}发布于 2013-06-05 20:40:08
您永远不会影响您创建的字典和您返回的变量。
https://stackoverflow.com/questions/16940144
复制相似问题