Search code examples
c#winformsregistry

Confused about how get RegistryKey value


I am really sorry for my poor english.I am wrting a program that reads version information of installed webBrowsers .The problem is that I am getting this exception below

An entry with the same key already exists.

This is the Path to registry keys of İnstalled browsers's

private const string AppPath = @"Software"

I am passing through the path value to my function and then I compare browserlist which is this

private readonly string[] _browserList ={"Google", "Mozilla"};

and subkeynames in the registry to find a match .

  void GetBrowserInfo(string path)
        {
            RegistryKey key = Registry.CurrentUser.OpenSubKey(AppPath);
           Dictionary<string,string>keyvalDictionary=new Dictionary<string, string>();
            try
            {
                if (key != null)
                {

                    string[] subKeys = key.GetSubKeyNames();
                    for (int i = 0; i < subKeys.Length; i++)
                    {
                        for (int j = 0; j < _browserList.Length; j++)
                        {
                            if (Array.IndexOf(subKeys, _browserList[j]) != -1)
                            {
                                RegistryKey openSubKey = Registry.CurrentUser.OpenSubKey(AppPath);
                                if (openSubKey != null)
                                {
                                    string pathds = Path.Combine(openSubKey.ToString(), _browserList[j]);
                                    string value= SelectedBrowser(_browserList[j],pathds);
                                    keyvalDictionary.Add(_browserList[j],value);

                                }


                            }
                        }
                    }

                }
            }
            catch (Exception e)
            {
                MessageBox.Show(e.ToString());
            }


        }




private string SelectedBrowser(string name ,string path)
        {
            string value = "";
            switch (name)
            {
                case "Google":
                    value = Registry.GetValue(path + "\\Chrome\\BLBeacon", "version", "").ToString();
                    break;
                case "Mozilla":
                    value = Registry.GetValue(path + @"\Mozilla Firefox\35.0 (x86 tr)\Uninstall", "Description", "").ToString();
                    break;

            }
            return value;
        }

This the the debug output enter image description here


Solution

  • You don't need outer loop. You are doing the same thing n times (where n is length of subKeys). Just drop this loop:

    for (int i = 0; i < subKeys.Length; i++)
    

    I think everything will work now.

    You were getting this exception, because after first iteration of subKeys loop you were adding the same keys to dictionary.