2010-07-24 74 views
9

因此,在我的注册表中,我有“LocalMachine \ SOFTWARE \ Microsoft \ Windows \ CurrentVersion \ Run \”下的条目,称为“COMODO Internet Security”,这是我的防火墙。现在我想知道的是如何获得注册表来检查该条目是否存在?如果它确实做到了这一点,如果不这样做。我知道如何检查子项“运行”是否存在,但不是“COMODO Internet Security”的条目,这是我用来获取子项是否存在的代码。如果注册表项存在,如果是这样做,如果不这样做

   using (RegistryKey Key = Registry.LocalMachine.OpenSubKey(@"SOFTWARE\Microsoft\Windows\CurrentVersion\Run\")) 
       if (Key != null) 
       { 

        MessageBox.Show("found"); 
       } 
       else 
       { 
        MessageBox.Show("not found"); 
       } 

回答

9

如果你正在寻找一个子项下的值,(就是你所说的“入口”?意思),你可以使用RegistryKey.GetValue(string)。如果它存在,将返回该值;如果不存在,则返回null。

例如:

using (RegistryKey Key = Registry.LocalMachine.OpenSubKey(@"SOFTWARE\Microsoft\Windows\CurrentVersion\Run\")) 
    if (Key != null) 
    {  
     string val = Key.GetValue("COMODO Internet Security"); 
     if (val == null) 
     { 
      MessageBox.Show("value not found"); 
     } 
     else 
     { 
      // use the value 
     } 
    } 
    else 
    { 
     MessageBox.Show("key not found"); 
    } 
+0

好吧,我如何得到它在localmachine与getvalue? – NightsEVil 2010-07-24 23:36:50

+0

添加示例。 – jwismar 2010-07-25 00:14:14

+0

错误不能将类型'object'隐式转换为'string'。存在明确的转换(您是否缺少演员?) – NightsEVil 2010-07-25 01:53:47

0

下面的链接应该澄清这一点:

How to check if a registry key/subkey already exists

示例代码:

using Microsoft.Win32; 

RegistryKey rk = Registry.LocalMachine.OpenSubKey("Software\\Geekpedia\\Test"); 

if(rk != null) 
{ 
    // It's there 
} 
else 
{ 
    // It's not there 
} 
+0

,但我需要寻找一个特定的启动项在本地机器当前用户微软窗口下运行 – NightsEVil 2010-07-24 23:37:43

+0

@Leniel:FYI:如果,例如,'Geekpedia'不在HLKM \ Software下的注册表中,VS2010会抛出一个尝试打开“'Software \\ Geekpedia \\ Test”键时的空引用异常。 – jp2code 2011-07-25 17:48:43

1

试试这个:

using (RegistryKey Key = Registry.LocalMachine.OpenSubKey(@"SOFTWARE\Microsoft\Windows\CurrentVersion\Run\COMODO Internet Security")) 
{ 
    if (Key != null) 
    MessageBox.Show("found"); 
    else 
    MessageBox.Show("not found"); 
} 
+0

但我需要寻找一个特定的启动条目下本地机器当前用户微软窗口运行 – NightsEVil 2010-07-24 23:36:29

0

最近我遇到了一个问题,我试图抓取注册表项中的子项,但问题是,由于我正在遍历注册表该部分中的每个注册表项,有时值不会有子项I正在寻找,并且当我尝试评估子项的值时,我会得到一个空引用异常。

所以,非常类似于一些其他的答案提供了什么,这是我结束了去:

string subkeyValue = null; 

var subKeyCheck = subkey.GetValue("SubKeyName"); 

if(subKeyCheck != null) 
{ 
    subkeyValue = subkey.GetValue("SubKeyName").ToString(); 
} 

那么根据什么子,你要寻找的价值,只是交换出来的“SubKeyName “这应该可以做到。

0

我的代码

 private void button2_Click(object sender, EventArgs e) 

    { 
     string HKCUval = textBox1.Text; 
     RegistryKey HKCU = Registry.CurrentUser; 
     //Checks if HKCUval exist. 
     try { 
      HKCU.DeleteSubKey(HKCUval); //if exist. 
     } 
     catch (Exception) 
     { 
      MessageBox.Show(HKCUval + " Does not exist"); //if does not exist. 
     } 

     } 

希望它能帮助。

相关问题