0

I want to set value for a registry key. When I try to use SetValue method it throws UnauthorizedAccessException exception, that says:

Attempted to perform an unauthorized operation.

This is my code:

var key = Microsoft.Win32.Registry.CurrentUser
            .OpenSubKey("SOFTWARE")
            .OpenSubKey("Microsoft")
            .OpenSubKey("Windows")
            .OpenSubKey("CurrentVersion")
            .OpenSubKey("Run", true);

if (key.GetValue("MyKey") == null)
{
    key.SetValue("MyKey", localPath, Microsoft.Win32.RegistryValueKind.String);
}
Yuliam Chandra
  • 14,494
  • 12
  • 52
  • 67
Saeed Hamed
  • 732
  • 2
  • 10
  • 28

2 Answers2

0

why don't you try with Registry Class??

below is the working code from my live server.

        RegistryKey registry = Registry.LocalMachine.OpenSubKey(@"software\newclient", true);            

        if (registry == null)
        {
            Registry.LocalMachine.CreateSubKey(@"software\newclient");
            registry = Registry.LocalMachine.OpenSubKey(@"software\newclient", true);
        }

        if (registry.GetValue("CreatedTime")==null)
        {
            registry.SetValue("CreatedTime", "1/1/1900 00:00 PM");
        }

        if (registry.GetValue("CurrentVersion") == null)
        {
            registry.SetValue("CurrentVersion", "0.0.0.0");
        }

        if (Convert.ToDateTime(registry.GetValue("CreatedTime").ToString()) != Convert.ToDateTime(arr[1]))
        {
            /*
             * other code snippet
             *
             */
            registry.SetValue("CurrentVersion",arr[0]);
            registry.SetValue("CreatedTime", arr[1]);

            return true;
        }

        registry.Close();
        return false;
Deepak Sharma
  • 4,124
  • 1
  • 14
  • 31
0

OpenSubKey can take 2 parameters, one of which is the subkey path, and the second can take the writable (bool) parameter

using(RegistryKey key = Registry.LocalMachine.OpenSubKey(@"SYSTEM\CurrentControlSet\Control\Session Manager\Environmen", true))
     {
         key.SetValue(saveValue, RegSelect);
     }