2012-10-23 143 views
2

谷歌今天沒有幫助我,所以我需要你的幫助。有沒有從註冊表中讀取值的可能方法?例如這個位置 - > HKEY_LOCAL_MACHINE> SOFTWARE>的myKey列是測試關鍵從註冊表中讀取價值

+3

你有看的Microsoft.Win32.RegistryKey的文檔? –

+5

我決定幫助你使用Google-Fu - 它可以使用一些改進。 https://www.google.com/search?q=read+registry+values+csharp – BTownTKD

+1

我該如何投票? –

回答

7

64位+ 32位

using Microsoft.Win32; 
    public static string GetRegistry() 
    { 
     string registryValue = string.Empty; 
     RegistryKey localKey = null; 
     if (Environment.Is64BitOperatingSystem) 
     { 
      localKey = RegistryKey.OpenBaseKey(Microsoft.Win32.RegistryHive.LocalMachine, RegistryView.Registry64); 
     } 
     else 
     { 
      localKey = RegistryKey.OpenBaseKey(Microsoft.Win32.RegistryHive.LocalMachine, RegistryView.Registry32); 
     } 

     try 
     { 
      localKey = localKey.OpenSubKey(@"Software\\MyKey"); 
      registryValue = localKey.GetValue("TestKey").ToString(); 
     } 
     catch (NullReferenceException nre) 
     { 

     } 
     return registryValue; 
    } 
+0

不錯,你給了這樣一個完整的答案 - 我個人重構了一點,因爲受你的'if'影響的唯一代碼是'RegistryView.Registry32' /'64'的值。 –

+1

我同意Puzey先生。此外,如果註冊表中不存在「MyKey」,或者由於某些其他原因導致讀取失敗,那麼localKey將爲空,您將得到一個異常。 try/catch語句應該在這裏使用。 – Fredrik

0

RTRY這樣的:

static object GetRegistryValue(string fullPath, object defaultValue) 
{ 
    string keyName = Path.GetDirectoryName(fullPath); 
    string valueName = Path.GetFileName(fullPath); 
    return Registry.GetValue(keyName, valueName, defaultValue); 
} 

,或者您可以使用Registry.LocalMachine 經過代碼項目這個http://www.csharphelp.com/2007/01/registry-ins-and-outs-using-c/