2010-07-24 86 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. 
     } 

     } 

希望它能幫助。

相關問題