简体   繁体   中英

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);
       }
   }
}

在此处输入图片说明

Try

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

(double '\\')

If not, try this answer .

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

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM