Как проверить, существует ли значение реестра с использованием C #? - PullRequest
70 голосов
/ 25 ноября 2010

Как проверить, существует ли значение реестра по коду C #?Это мой код, я хочу проверить, существует ли «Старт».

public static bool checkMachineType()
{
    RegistryKey winLogonKey = Registry.LocalMachine.OpenSubKey(@"System\CurrentControlSet\services\pcmcia", true);
    string currentKey= winLogonKey.GetValue("Start").ToString();

    if (currentKey == "0")
        return (false);
    return (true);
}

Ответы [ 7 ]

55 голосов
/ 25 ноября 2010

Для ключа реестра вы можете проверить, является ли он нулевым после его получения. Так будет, если его не будет.

Для значения реестра вы можете получить имена значений для текущего ключа и проверить, содержит ли этот массив необходимое имя значения.

Пример:

public static bool checkMachineType()
{    
    RegistryKey winLogonKey = Registry.LocalMachine.OpenSubKey(@"System\CurrentControlSet\services\pcmcia", true);
    return (winLogonKey.GetValueNames().Contains("Start"));
}
40 голосов
/ 10 сентября 2012
public static bool RegistryValueExists(string hive_HKLM_or_HKCU, string registryRoot, string valueName)
{
    RegistryKey root;
    switch (hive_HKLM_or_HKCU.ToUpper())
    {
        case "HKLM":
            root = Registry.LocalMachine.OpenSubKey(registryRoot, false);
            break;
        case "HKCU":
            root = Registry.CurrentUser.OpenSubKey(registryRoot, false);
            break;
        default:
            throw new System.InvalidOperationException("parameter registryRoot must be either \"HKLM\" or \"HKCU\"");
    }

    return root.GetValue(valueName) != null;
}
24 голосов
/ 25 ноября 2010
string keyName=@"HKEY_LOCAL_MACHINE\System\CurrentControlSet\services\pcmcia";
string valueName="Start";
if (Registry.GetValue(keyName, valueName, null) == null)
{
     //code if key Not Exist
}
else
{
     //code if key Exist
}
2 голосов
/ 10 сентября 2012
  RegistryKey rkSubKey = Registry.CurrentUser.OpenSubKey(" Your Registry Key Location", false);
        if (rkSubKey == null)
        {
           // It doesn't exist
        }
        else
        {
           // It exists and do something if you want to
         }
0 голосов
/ 13 мая 2019
public bool ValueExists(RegistryKey Key, string Value)
{
   try
   {
       return Key.GetValue(Value) != null;
   }
   catch
   {
       return false;
   }
}

Эта простая функция будет возвращать true, только если значение найдено, но оно не равно нулю, иначе вернет false, если значение существует, но оно равно нулю или значение не существует в ключе.


ИСПОЛЬЗОВАНИЕ для вашего вопроса:

if (ValueExists(winLogonKey, "Start")
{
    // The values exists
}
else
{
    // The values does not exists
}
0 голосов
/ 30 апреля 2017
        RegistryKey test9999 = Registry.CurrentUser;

        foreach (var item in test9999.GetSubKeyNames())
        {
            if (item.ToString() == "SOFTWARE")
            {
                test9999.OpenSubKey(item);

                foreach (var val in test9999.OpenSubKey(item).GetSubKeyNames())
                {
                    if(val.ToString() == "Adobe") {
                        Console.WriteLine(val+ " found it ");
                    }
                }
            }
        }
0 голосов
/ 08 сентября 2016
        internal static Func<string, string, bool> 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:
        /* 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
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...