1

我尝试用 UI 编写一个简单的 C# 程序来在注册表中添加我自己的键和值。我将它添加到注册表,以便我的程序稍后启动时可以读取它并且不会重新配置自身。

RegistryKey rk =  LocalMachine.OpenSubKey("HKEY_LOCAL_MACHINE\\SOFTWARE\\AMC", RegistryKeyPremissionsCheck.ReadWriteSubTree, RegistryRights.ChangePermissions | RegistryRights.ReadKey);//Get the registry key desired with ChangePermissions Rights.
RegistrySecurity rs = new RegistrySecurity();
rs.AddAccessRule(new RegistryAccessRule("Administrator", RegistryRights.FullControl, InheritanceFlags.ContainerInherit | InheritanceFlags.ObjectInherit, PropagationFlags.InheritOnly, AccessControlType.Allow));//Create access rule giving full control to the Administrator user.
rk.SetAccessControl(rs); //Apply the new access rule to this Registry Key.
rk = LocalMachine.OpenSubKey("HKEY_LOCAL_MACHINE\\SOFTWARE\\AMC", RegistryKeyPremissionsCheck.ReadWriteSubTree, RegistryRights.FullControl); // Opens the key again with full control.
rs.SetOwner(new NTAccount("Administrator"));// Set the securitys owner to be Administrator
rk.SetAccessControl(rs);// Set the key with the changed permission so Administrator is now owner.

这是我从 Stackoverflow 的一些问题中获得的代码。我试图在添加/删除/修改密钥时解决权限问题。

我错过了什么吗?

4

1 回答 1

2

在您使用的第一行中,RegistryKeyPremissionsCheck这是您尚未定义的变量。也一样LocalMachine。写行

RegistryKey LocalMachine = Registry.LocalMachine;

在您的代码之前LocalMachine

至于如果你想编辑你正在打开的子键下的值RegistryKeyPremissionsCheck.ReadWriteSubTree替换它,否则你可以放在那里truefalse

如果您只想向注册表添加密钥,我会使用 -

int MyNumber = 0; // Your value, doesnt have to be a number
Registry.SetValue("HKEY_LOCAL_MACHINE\\SOFTWARE\\AMC", "My User Name", MyNumber);

并获得价值

object val = Registry.GetValue("HKEY_LOCAL_MACHINE\\SOFTWARE\\AMC", "My User Name", -1);

现在我放了这段代码,如果你有正确的权限(你是管理员)它就可以工作

RegistryKey LocalMachine = Registry.LocalMachine;
         RegistryKey rk = LocalMachine.OpenSubKey("HKEY_LOCAL_MACHINE\\SOFTWARE\\AMC",
            RegistryKeyPermissionCheck.ReadWriteSubTree, RegistryRights.ChangePermissions | RegistryRights.ReadKey);//Get the registry key desired with ChangePermissions Rights.
         RegistrySecurity rs = new RegistrySecurity();
         rs.AddAccessRule(new RegistryAccessRule("Administrator", RegistryRights.FullControl, InheritanceFlags.ContainerInherit | InheritanceFlags.ObjectInherit, PropagationFlags.InheritOnly, AccessControlType.Allow));//Create access rule giving full control to the Administrator user.
         rk.SetAccessControl(rs); //Apply the new access rule to this Registry Key.
         rk = LocalMachine.OpenSubKey("HKEY_LOCAL_MACHINE\\SOFTWARE\\AMC",
            RegistryKeyPermissionCheck.ReadWriteSubTree, RegistryRights.FullControl); // Opens the key again with full control.
         rs.SetOwner(new NTAccount("Administrator"));// Set the securities owner to be Administrator
         rk.SetAccessControl(rs);
         int MyNumber = 0; // Your value, doesn't have to be a number
         rk.SetValue("username", MyNumber);// The username should by the dynamic part
于 2013-07-29T09:09:38.783 回答