How to check if a registry value exists using C#?

后端 未结 7 1386
庸人自扰
庸人自扰 2020-12-08 13:28

How to check if a registry value exists by C# code? This is my code, I want to check if \'Start\' exists.

public static bool checkMachineType()
{
    Registr         


        
7条回答
  •  时光说笑
    2020-12-08 13:43

            internal static Func regKey = delegate (string KeyLocation, string Value)
            {
                // get registry key with Microsoft.Win32.Registrys
                RegistryKey rk = (RegistryKey)Registry.GetValue(KeyLocation, Value, null); // KeyLocation and Value variables from method, null object because no default value is present. Must be casted to RegistryKey because method returns object.
                if ((rk) == null) // if the RegistryKey is null which means it does not exist
                {
                    // the key does not exist
                    return false; // return false because it does not exist
                }
                // the registry key does exist
                return true; // return true because it does exist
            };
    

    usage:

            // usage:
            /* Create Key - while (loading)
            {
                RegistryKey k;
                k = Registry.CurrentUser.CreateSubKey("stuff");
                k.SetValue("value", "value");
                Thread.Sleep(int.MaxValue);
            }; // no need to k.close because exiting control */
    
    
            if (regKey(@"HKEY_CURRENT_USER\stuff  ...  ", "value"))
            {
                 // key exists
                 return;
            }
            // key does not exist
    

提交回复
热议问题