問題描述
嘗試使用 C# 設置註冊表權限時出現 NullReferenceException (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);
}
}
}
參考解法
方法 1:
Try
@"\\SOFTWARE\\Wow6432Node\\123Test"
(double '\')
If not, try this answer.
方法 2:
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
方法 3:
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);
(by JimDel、Sam Leach、Fishcake、Ehsan)