/// <summary> /// Retrieves a list of the members of a particular local group in the security database. /// </summary> /// <param name="GroupName"> /// The name of the local group whose members are to be listed. /// </param> /// <returns> /// Returns an array of security identifiers (SIDs), each representing a group member. /// </returns> private static SecurityIdentifier[] GetLocalGroupMembers(string GroupName) { SecurityIdentifier[] returnValue = null; IntPtr buffer = IntPtr.Zero; IntPtr Resume = IntPtr.Zero; int val = NativeMethods.NetLocalGroupGetMembers(null, GroupName, 0, out buffer, -1, out int EntriesRead, out int TotalEntries, Resume); if (EntriesRead > 0) { returnValue = new SecurityIdentifier[EntriesRead]; NativeMethods.LOCALGROUP_MEMBERS_INFO_0[] Members = new NativeMethods.LOCALGROUP_MEMBERS_INFO_0[EntriesRead]; IntPtr iter = buffer; for (int i = 0; i < EntriesRead; i++) { Members[i] = (NativeMethods.LOCALGROUP_MEMBERS_INFO_0)System.Runtime.InteropServices.Marshal.PtrToStructure(iter, typeof(NativeMethods.LOCALGROUP_MEMBERS_INFO_0)); iter = (IntPtr)((long)iter + System.Runtime.InteropServices.Marshal.SizeOf(typeof(NativeMethods.LOCALGROUP_MEMBERS_INFO_0))); if (Members[i].lgrmi0_sid != IntPtr.Zero) { SecurityIdentifier sid = new SecurityIdentifier(Members[i].lgrmi0_sid); returnValue[i] = sid; } else { returnValue[i] = null; } } NativeMethods.NetApiBufferFree(buffer); } return(returnValue); }
/// <summary> /// Removes a security identifier (SID) from a local security group. /// </summary> /// <param name="GroupName"> /// The name of the group from which the SID is to be removed. /// </param> /// <param name="memberSid"> /// The security identifier (SID) to be removed from the local group. /// </param> /// <returns> /// If the removal of the group member is successful, this function returns /// zero (0). Otherwise, a non-zero value is returned. /// </returns> private static int RemoveLocalGroupMembers(string GroupName, SecurityIdentifier memberSid) { int returnValue = -1; NativeMethods.LOCALGROUP_MEMBERS_INFO_0 memberInfo = new NativeMethods.LOCALGROUP_MEMBERS_INFO_0(); byte[] binarySid = new byte[memberSid.BinaryLength]; memberSid.GetBinaryForm(binarySid, 0); IntPtr unmanagedPointer = System.Runtime.InteropServices.Marshal.AllocHGlobal(binarySid.Length); System.Runtime.InteropServices.Marshal.Copy(binarySid, 0, unmanagedPointer, binarySid.Length); memberInfo.lgrmi0_sid = unmanagedPointer; returnValue = NativeMethods.NetLocalGroupDelMembers(null, GroupName, 0, ref memberInfo, 1); System.Runtime.InteropServices.Marshal.FreeHGlobal(unmanagedPointer); return(returnValue); }