如何使用c#在远程计算机上设置注册表访问规则

我正在尝试在远程计算机上设置注册表访问规则:

using (RegistryKey localMachineKey = RegistryKey.OpenRemoteBaseKey(RegistryHive.LocalMachine, serverName))
{
  RegistrySecurity rs = new RegistrySecurity();
  rs.AddAccessRule(new RegistryAccessRule(userName, RegistryRights.FullControl, AccessControlType.Allow));

  using (RegistryKey subKey = localMachineKey.CreateSubKey(registryKey))
  {
    subKey.SetValue(name, value);
    subKey.SetAccessControl(rs);
  }
}

这会产生以下异常:

    System.NotSupportedException: The supplied handle is invalid. This can happen when trying to set an ACL on an anonymous kernel object.
   at System.Security.AccessControl.NativeObjectSecurity.Persist(String name, SafeHandle handle, AccessControlSections includeSections, Object exceptionContext)
   at System.Security.AccessControl.NativeObjectSecurity.Persist(SafeHandle handle, AccessControlSections includeSections, Object exceptionContext)
   at System.Security.AccessControl.RegistrySecurity.Persist(SafeRegistryHandle hKey, String keyName)...

有谁知道如何使这工作?
谢谢!

最佳答案 使用WinRM可能是一种选择.

How to access WinRM in C#

此链接表明此信息以及更多信息:

http://social.technet.microsoft.com/Forums/en-US/winserverpowershell/thread/0beee366-ee8d-4052-b1b9-8ad9bf0f8ff0/

部分链接表明无法远程设置.但是,在底部,Shaka_01提到了调用.SetAccessRuleProtection.

RegistryKey rk = RegistryKey.OpenRemoteBaseKey(...);
RegistrySecurity rs = rk.GetAccessControl(AccessControlSections.All);
rs.SetAccessRuleProtection(true, true); //this line you need to set  ACL on a remote machines registry key.
点赞