2010-04-27 45 views
17

這不是爲我工作:C#中註冊本地計算機創造價值

public bool createRegistry() 
{ 
    if (!registryExists()) 
    { 
     Microsoft.Win32.Registry.LocalMachine.CreateSubKey("Software\\xelo\\"); 

     Microsoft.Win32.Registry.LocalMachine.OpenSubKey("Software\\xelo").SetValue("hostname", (string)hostname, Microsoft.Win32.RegistryValueKind.String); 


     return true; 
    } 
    else 
    { 
     return updateRegistry(); 
    } 

}

異常錯誤是無權做的事情。任何幫助,將apreaciated

Exeption:System.UnauthorizedAccessException | "Cannot write to the registry key"

對於工作復讀上接受的解決方案

回答

24

非管理員和unelevated admin用戶評論無權修改HKEY_LOCAL_MACHINE關鍵。以管理員身份運行程序。

+4

我是管理員,並以管理員身份運行給我相同的錯誤 – 2010-04-27 17:22:05

+0

檢查在regedit中的密鑰的權限。 – Segfault 2010-04-27 17:28:37

+11

嘗試將true傳遞給OpenSubKey調用的第二個參數或使用CreateSubKey的返回值。 http://msdn.microsoft.com/en-us/library/microsoft.win32.registrykey.opensubkey.aspx http://msdn.microsoft.com/en-us/library/ad51f2dx%28v=VS .100%29.aspx – 2010-04-27 17:32:26

0

那麼你已經得到了你的答案 - 我猜你正在Vista或Windows 7(或Server 2008)上運行,並且運行該應用程序的進程/用戶沒有修改註冊表的權限/權限。

所以它不是一個代碼問題,而是一個系統管理員。構建應用程序並以管理員身份運行,看看是否有效。

+1

甚至與管理員相同的錯誤 – 2010-04-27 17:23:21

+0

我可以確認以上述代碼片段中所建議的方式編程更新帶有管理權限的HKEY_LOCAL_MACHINE,並且接受的答案不起作用。 – Cole 2014-12-18 17:00:53

7

即使管理員我不認爲你可以從LocalMachine創建新的密鑰。請確保你做

Registry.LocalMachine.CreateSubKey(@"SOFTWARE\YourCompanyName\SomeNewKey"); 

,而不是

Registry.LocalMachine.CreateSubKey("SomeNewKey"); 
+0

準確地說,在VS上面運行這段代碼,或者進入'/ bin/Debug/App.exe'並以Admin身份運行導致下面的錯誤: '在mscorlib中發生未處理的異常'System.UnauthorizedAccessException' .dll 其他信息:訪問註冊表項'HKEY_LOCAL_MACHINE \ SOFTWARE \ YourCompanyName \ SomeNewKey'被拒絕。' – Cole 2014-12-18 16:59:23

+0

@Cole:您可能想發佈一個新問題,其中包含特定於您的問題的詳細信息。這種寫入註冊表的方法是可靠的,我已經在商業軟件中使用了多年。如果你發佈你的代碼,我們可以幫你弄清楚爲什麼你會得到這個異常。我的典型模式是:'RegistryKey rk = Registry.LocalMachine。OpenSubKey(path,true);如果(rk == null){rk = Registry.LocalMachine.CreateSubKey(path);} if(rk!= null){.. do stuff .. rk.Close(); }' – nothingisnecessary 2014-12-18 17:27:49

+1

'string path = @「SOFTWARE \ Microsoft \ Windows \ CurrentVersion \ Authentication \ Credential Providers」; 的RegistryKey的RegistryKey = Registry.LocalMachine.OpenSubKey(路徑,TRUE);' ,其拋出 '類型的未處理的異常 'System.Security.SecurityException' 出現在mscorlib.dll 附加信息:請求的註冊表訪問是不允許。' – Cole 2014-12-18 23:52:25

-2

將Premission校驗位真...

Microsoft.Win32.Registry.LocalMachine.CreateSubKey("Software\\xelo\\", true); 

:)

+2

Registry.LocalMachine不包含任何重載方法,它允許[ CreateSubKey(String,Bool)](http://msdn.microsoft.com/en-us/library/Microsoft.Win32.RegistryKey.CreateSubKey(v = vs.110).aspx) – WiiMaxx 2014-08-06 06:56:46

6

下面的代碼來創建關鍵註冊表。

Microsoft.Win32.RegistryKey key; 
key = Microsoft.Win32.Registry.LocalMachine.CreateSubKey("Software\\Wow6432Node\\Names"); 
key.SetValue("Name", "Isabella"); 
key.Close(); 
+1

我收到了一個'Additional information:Access運行代碼段時,註冊表項'HKEY_LOCAL_MACHINE \ Software \ Wow6432Node \ Names'被拒絕.'錯誤。請指教。 – Cole 2014-12-18 16:54:54

+0

以管理員身份運行應用程序,它應該工作。 – PandaNL 2015-03-12 14:51:01

相關問題