JimDel
JimDel

Reputation: 4359

NullReferenceException when trying to set registry permissions with C#

I'm trying to set the below permissions on a registry key. But I get a NullReferenceException error when it tries. Being a novice makes this tuff. Throw in permissions (which have always confused me) and I'm stumped. Can someone tell me why I'm getting this? Thanks.

using System;
using Microsoft.Win32;
using System.Security.AccessControl;

namespace ConsoleApplication7
{
   class Program
   {
       static void Main(string[] args)
       {
           RegistrySecurity rs = new RegistrySecurity();
           string user = "Everyone";

           RegistryKey rk = Registry.LocalMachine.OpenSubKey(@"\SOFTWARE\Wow6432Node\123Test", true);

           rs.AddAccessRule(new RegistryAccessRule(user,
               RegistryRights.FullControl | RegistryRights.TakeOwnership,
               InheritanceFlags.ContainerInherit,
               PropagationFlags.None,
               AccessControlType.Allow));

           rk.SetAccessControl(rs);
       }
   }
}

enter image description here

Upvotes: 0

Views: 190

Answers (3)

Ehsan
Ehsan

Reputation: 32729

This line is causing you error

 RegistryKey rk = Registry.LocalMachine.OpenSubKey(@"\SOFTWARE\Wow6432Node\123Test", true);

Place a debugger here and see if it has value or it is null. If it is null check that path is valid. If it is valid do it like this

RegistryKey rk = Registry.LocalMachine.OpenSubKey(@"\\SOFTWARE\\Wow6432Node\\123Test", true);

Upvotes: 1

Fishcake
Fishcake

Reputation: 10784

Most likely the nullreference exception is on the RegistryKey rk itself.

Is your application running as a 32-bit or 64-bit application? You shouldn't need to specify the Wow6432Node part and should just be able to reference @"\SOFTWARE\123Test

Upvotes: 1

Sam Leach
Sam Leach

Reputation: 12966

Try

@"\\SOFTWARE\\Wow6432Node\\123Test"

(double '\')

If not, try this answer.

Upvotes: 1

Related Questions