错误的值计数

时间:2014-06-27 22:22:28

标签: c# .net registry

我正在尝试获取所有初创公司的程序,但我的计数错误。

我这样做:

    private const int m_HKCU_PATH_CODE = 0;
    private const int m_HKLM_PATH_CODE = 1;
    private const string m_REGISTRY_PATH = @"Software\Microsoft\Windows\CurrentVersion\Run";

[...]

        m_InitialStartupPrograms = new Dictionary<string, int>();

        m_RegistryKey = Registry.CurrentUser.OpenSubKey(m_REGISTRY_PATH);
        foreach (string startupPrograms in m_RegistryKey.GetValueNames())
            m_InitialStartupPrograms.Add(startupPrograms, m_HKCU_PATH_CODE);

        m_RegistryKey.Close();

        m_RegistryKey = Registry.LocalMachine.OpenSubKey(m_REGISTRY_PATH);
        foreach (string startupPrograms in m_RegistryKey.GetValueNames())
            m_InitialStartupPrograms.Add(startupPrograms, m_HKLM_PATH_CODE);

        m_RegistryKey.Close();

但我只有11个启动程序,而注册表包含14个启动程序。 实际上,所有缺少的statup程序都在LocalMachine中。我正确地在CurrentUser中获取所有启动程序。

编辑:我真的不明白......

http://puu.sh/9N1pd/86ffb17fed.png

在屏幕上,我们可以看到它是相同的文件夹,但有不同的键! (感谢CCleaner访问了文件夹。)

1 个答案:

答案 0 :(得分:1)

您的程序是否在64位计算机上作为32位程序运行?如果是,你真的在​​看Software\Wow6432Node\Microsoft\Windows\CurrentVersion\Run

如果您使用的是.NET 4或更高版本,您可以告诉它通过OpenBaseKey检查哪个文件夹

这是一个使用它的程序的清理版本。

private void Init()
{
    m_InitialStartupPrograms = new Dictionary<string, int>();

    LoadDictionary(RegistryHive.LocalMachine, RegistryView.Registry32, m_HKLM_PATH_CODE);
    LoadDictionary(RegistryHive.LocalMachine, RegistryView.Registry64, m_HKLM_PATH_CODE);
    LoadDictionary(RegistryHive.CurrentUser, RegistryView.Registry32, m_HKCU_PATH_CODE);
    LoadDictionary(RegistryHive.CurrentUser, RegistryView.Registry64, m_HKCU_PATH_CODE);
}

//Instead of repeating the same code over and over, make a function then just 
// call the function repeatedly with different parameters.
private void LoadDictionary(RegistryHive hive, RegistryView view, int pathCode)
{
    //based on the name m_RegistryKey it appears that those where not local variables.
    //Because you close them right away there is no reason not to make them local
    // variables inside using statements.

    using (var baseKey = RegistryKey.OpenBaseKey(hive, view))
    using (var subKey = baseKey.OpenSubKey(m_REGISTRY_PATH))
    {
        foreach (string startupPrograms in subKey.GetValueNames())
        {
            m_InitialStartupPrograms.Add(startupPrograms, pathCode);
        }
    }
}