private RegistryKey GetRegistryKey(REGISTRY_ROOT Root, string KeyPath, RegistryRights Desired) { try { switch (Root) { case REGISTRY_ROOT.HKEY_CLASSES_ROOT: return(Registry.ClassesRoot.OpenSubKey(KeyPath, RegistryKeyPermissionCheck.ReadWriteSubTree, Desired)); case REGISTRY_ROOT.HKEY_LOCAL_MACHINE: return(Registry.LocalMachine.OpenSubKey(KeyPath, RegistryKeyPermissionCheck.ReadWriteSubTree, Desired)); case REGISTRY_ROOT.HKEY_USERS: return(Registry.Users.OpenSubKey(KeyPath, RegistryKeyPermissionCheck.ReadWriteSubTree, Desired)); case REGISTRY_ROOT.HKEY_CURRENT_USER: return(Registry.CurrentUser.OpenSubKey(KeyPath, RegistryKeyPermissionCheck.ReadWriteSubTree, Desired)); default: return(null); } } catch (Exception) { return(null); } }
public void SetRegistryOwner(REGISTRY_ROOT Root, string KeyPath, SecurityIdentifier sid) { long win32ErrorCode = 0; SECURITY_DESCRIPTOR sd = new SECURITY_DESCRIPTOR(); byte[] byteSid = new byte[sid.BinaryLength]; sid.GetBinaryForm(byteSid, 0); IntPtr pRegKey = IntPtr.Zero; try { win32ErrorCode = RegOpenKeyEx(Root, KeyPath, 0, SAM_DESIRED.WRITE_OWNER, ref pRegKey); if (win32ErrorCode != 0) { throw new RegistryKeyOpenException(win32ErrorCode); } } catch (RegistryKeyOpenException) { throw; } catch (Exception ex) { throw new RegistryKeyOpenException(ex); } InitializeSecurityDescriptor(ref sd, 1); SetSecurityDescriptorOwner(ref sd, byteSid, 0); try { win32ErrorCode = RegSetKeySecurity(pRegKey, SECURITY_INFORMATION.OWNER_SECURITY_INFORMATION, sd); if (win32ErrorCode != 0) { throw new RegistryKeySetSecurityException(win32ErrorCode); } } catch (RegistryKeySetSecurityException) { throw; } catch (Exception ex) { throw new RegistryKeyOpenException(ex); } finally { RegCloseKey(pRegKey); } }
public static extern int RegUnLoadKey(REGISTRY_ROOT hKey, string lpSubKey);
public static extern long RegOpenKeyEx(REGISTRY_ROOT hKey, string lpSubKey, long ulOptions, SAM_DESIRED samDesired, ref IntPtr ptrKey);