Как проверить на C #, если запись реестра существует или нет [дублировать]

nth-of-type работает в соответствии с индексом того же типа элемента, но nth-child работает только в соответствии с индексом независимо от того, какой тип элементов сиблингов.

Например

<div class="one">...</div>
<div class="two">...</div>
<div class="three">...</div>
<div class="four">...</div>
<div class="five">...</div>
<div class="rest">...</div>
<div class="rest">...</div>
<div class="rest">...</div>
<div class="rest">...</div>
<div class="rest">...</div>

Предположим, что в выше html мы хотим скрыть все элементы, имеющие класс отдыха.

В этом случае nth-child и nth-of-type будут работать точно так же, как и все элементы одного типа, <div>, поэтому css должен быть

.rest:nth-child(6), .rest:nth-child(7), .rest:nth-child(8), .rest:nth-child(9), .rest:nth-child(10){
    display:none;
}

OR

.rest:nth-of-type(6), .rest:nth-of-type(7), .rest:nth-of-type(8), .rest:nth-of-type(9), .rest:nth-of-type(10){
    display:none;
}

Теперь вам должно быть интересно узнать, в чем разница между nth-child и nth-of-type, так что это разница

Предположим, что html is

<div class="one">...</div>
<div class="two">...</div>
<div class="three">...</div>
<div class="four">...</div>
<div class="five">...</div>
<p class="rest">...</p>
<p class="rest">...</p>
<p class="rest">...</p>
<p class="rest">...</p>
<p class="rest">...</p>

В приведенном выше html тип элемента .rest отличается от других .rest - это абзацы, а другие - div, поэтому в этом случае if вы используете nth-child, вы должны писать так

.rest:nth-child(6), .rest:nth-child(7), .rest:nth-child(8), .rest:nth-child(9), .rest:nth-child(10){
    display:none;
}

, но если вы используете nss-тип css, это может быть

.rest:nth-of-type(1), .rest:nth-of-type(2), .rest:nth-of-type(3), .rest:nth-of-type(4), .rest:nth-of-type(5){
    display:none;
}

Как тип Элементом .rest является <p>, поэтому здесь nth-of-type обнаруживает тип .rest, а затем он накладывает css на 1-й, 2-й, 3-й, 4-й, 5-й элементы <p>.

61
задан Igor Brejc 10 July 2012 в 08:28
поделиться

6 ответов

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

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

47
ответ дан 26071986 19 August 2018 в 20:00
поделиться
        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
ответ дан awfullyCold 19 August 2018 в 20:00
поделиться
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
}
22
ответ дан Ben Gripka 19 August 2018 в 20:00
поделиться
  • 1
    Что, если значение ключа "not exist"? Это означает, что defaultValue не предназначен для проверки наличия ключа, это означает, что для предотвращения дополнительной проверки нулевого значения. – abatishchev 25 November 2010 в 12:23
  • 2
    @ben изменил значение по умолчанию от "not exist" до null (тем самым зафиксировав код). Поэтому предыдущий комментарий от @abatishchev больше не применяется. – Sebastian Krysmanski 5 October 2015 в 13:59
        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
-2
ответ дан Coomphs 19 August 2018 в 20:00
поделиться
  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
         }
4
ответ дан C_sharp 19 August 2018 в 20:00
поделиться
  • 1
    это решение - проверить, существует или нет ключ. для значения мы должны проверить список значений в этом ключе – jammy 3 December 2014 в 10:22
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;
}
36
ответ дан JimiLoe 19 August 2018 в 20:00
поделиться
  • 1
    Хотя этот ответ определенно правильный, на этот вопрос уже был дан ответ. – hsanders 10 September 2012 в 20:55
  • 2
    @hsanders, даже если вопрос уже был дан, всегда можно добавить полезную информацию. Переполнение стека получает большой трафик от Google;) – DonkeyMaster 5 August 2013 в 16:02
  • 3
    root.GetValue (valueName)! = null вызывает исключение, если valueName не существует. – Farukh 2 August 2016 в 20:19
  • 4
  • 5
Другие вопросы по тегам:

Похожие вопросы: