Modify an existing registry key value in c#

可紊 提交于 2019-12-23 16:59:45

问题


I want to modify a data in registry path SOFTWARE\Wow6432Node\Program\SubProgram using C# code in windows 7. I am able to read the value but I can't write into Registry. Here is the code:

RegistryKey SUBKEY;
RegistryKey TAWKAY = RegistryKey.OpenRemoteBaseKey(Microsoft.Win32.RegistryHive.LocalMachine, "");
string subkey = "SOFTWARE\\Wow6432Node\\Program\\SubProgram ";
if (TAWKAY.OpenSubKey(subkey) != null)   // Get values from Registry
{

    TAWKAY = RegistryKey.OpenRemoteBaseKey(Microsoft.Win32.RegistryHive.LocalMachine, "");
    SUBKEY = TAWKAY.OpenSubKey(subkey); // subkey opens
    SUBKEY = TAWKAY.OpenSubKey(subkey,true); // subkey not open shows error Requested registry access is not allowed 
    SUBKEY.SetValue("Some name", "1234567890");
    Console.WriteLine(SUBKEY.GetValue("Some name").ToString());
}
else
{
    Console.WriteLine("Cannot open registry");
}

Console.Read();

If I set OpenSubKey(subkey, true), it shows an error message Requested registry access is not allowed

Is there any permission needed to write into registry? Please help me to solve the issue


回答1:


Wow6432Node is not a real path in the registry. It is an alias for 32 bit keys in 64 bit OS.

You must use RegistryView.Registry32 in order to specify you want to work with 32 bits.

RegistryKey reg32key = RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, RegistryView.Registry32);
RegistryKey reg_32bit_AppKey = reg32key.OpenSubKey(@"SOFTWARE\Program\SubProgram");
if (reg_32bit_AppKey != null)
{
    // Here you can work with "SOFTWARE\\Wow6432Node\\Program\\SubProgram "
}



回答2:


Modifying/deleting/adding keys in HKLM requires administrator rights.

In that case you want to do that you will need to change your applications manifest requestedExecutionLevel value to requireAdministrator




回答3:


It is better to use "Reg" command inorder to perform any operation on registry.

Even though if you want to access the registry of remote machine you don't nedd credentials of that machine, having the machine name is sufficient.

For more information about "REG" command refer to the following link

http://technet.microsoft.com/en-us/library/cc732643(v=ws.10).aspx



来源:https://stackoverflow.com/questions/15675825/modify-an-existing-registry-key-value-in-c-sharp

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!