C# Read Form Registry Snippet

This article has been written before more than 24months, information might old.

C# method , example to read from registry .

        static string ReadKey(string keyLoc)
        {
            // Usage : 
            // Example : ReadKey(@"HKEY_CURRENT_USER\Software\Valve\HLServer\InstallPath") shoud return similar to K:\valve\hlserver 
            // the data after the last \ is the value name .
            // In case of error a string with the error will be returned
            RegistryKey Hive;
            Regex RTest1 = new Regex(@"HKEY_CURRENT_USER\\|HKCU\\"); // HKCU
            if (RTest1.IsMatch(keyLoc)){ Hive = Registry.CurrentUser; }else
            { RTest1 = null; Regex RTest2 = new Regex(@"HKEY_LOCAL_MACHINE\\|HKLM\\"); // HKLM
            if (RTest2.IsMatch(keyLoc)){ Hive = Registry.LocalMachine; }else
            { RTest2 = null; Regex RTest3 = new Regex(@"HKEY_CLASSES_ROOT\\|HKCR\\"); // HKCR
            if (RTest3.IsMatch(keyLoc)){ Hive = Registry.ClassesRoot; }else
            { RTest3 = null; Regex RTest4 = new Regex(@"HKEY_USERS\\|HKU\\"); // HKU
            if (RTest4.IsMatch(keyLoc)){ Hive = Registry.Users; } else
            { RTest4 = null; Regex RTest5 = new Regex(@"HKEY_CURRENT_CONFIG\\|HKC\\"); // HKCC
            if (RTest5.IsMatch(keyLoc)){ Hive = Registry.CurrentConfig; }
            else{RTest5 = null; return "Invalid registry hive name please check you key name ";
            }}}}}
            Regex RTs1 = new Regex(@"\\");
            string[] RTarr = RTs1.Split(keyLoc);
            string StrSubKey = "";
            for (int i = 0; i < RTarr.Length - 2; i++) StrSubKey = StrSubKey + RTarr[i + 1] + @"\";
            RegistryKey HiveSubKey = Hive.OpenSubKey(@StrSubKey);
            if (HiveSubKey == null)
            {
                Hive.Close();
                return "Registry key does not exist.";
            }
            else
            {
                string ret = HiveSubKey.GetValue(RTarr[RTarr.Length - 1]).ToString();
                if (ret == null)
                {
                    Hive.Close(); HiveSubKey.Close();
                    return " Value name does not exist.";
                }
                else
                {
                    Hive.Close(); HiveSubKey.Close();
                    return ret;
                }
            }
        }

All the snippets on this blog were wrote by me , thus could be better ways to write the above snippet , thanks for understanding .

Share the joy

Leave a Reply