简体   繁体   中英

Removing a User From an Active Directory Group

I'm trying to remove a certain user from an Active Directory group using C#. Here is my piece of code which should handle my task, even though it does not currently work.

public static bool RemoveUserFromGroup(string UserId, string GroupId)
{
    using (var directory = new DirectoryEntry("LDAP://server"))
    {
        using (var dSearch = new DirectorySearcher(directory))
        {
            try
            {
                dSearch.Filter = "(sAMAccountName=" + UserId + ")";
                SearchResult sr = dSearch.FindOne();
                System.DirectoryServices.PropertyCollection UserProperties = sr.GetDirectoryEntry().Properties;
                if(UserProperties == null)
                    return false;
                foreach(object Group in UserProperties["memberOf"])
                {
                    if(Group.ToString() == GroupId)
                    {
                        UserProperties["memberOf"].Remove(GroupId);
                        directory.CommitChanges();
                        directory.Close();
                        return true;
                    }
                }
            }
            catch (Exception e)
            {
                return false;
            }
        }
    }
    return false;
}

Please excuse me if there are any typos within this code, I had to manually copy it from the machine I am developing on, which has no internet access sadly.

Use :

public void RemoveUserFromGroup(string userId, string groupName)
{   
    try 
    { 
        using (PrincipalContext pc = new PrincipalContext(ContextType.Domain, "COMPANY"))
        {
            GroupPrincipal group = GroupPrincipal.FindByIdentity(pc, groupName);
            group.Members.Remove(pc, IdentityType.UserPrincipalName, userId);
            group.Save();
        }
    } 
    catch (System.DirectoryServices.DirectoryServicesCOMException E) 
    { 
        //doSomething with E.Message.ToString(); 

    }
}
 public string RemoveUserFromList(string UserID, string ListName)
    {
        try
        {
            using (PrincipalContext pc = new PrincipalContext(ContextType.Domain, "DomainName", UserName, Password))
            {
                GroupPrincipal group = GroupPrincipal.FindByIdentity(pc, ListName);
                group.Members.Remove(pc, IdentityType.SamAccountName, UserID);
                group.Save();
            }
            return "Success";
        }
        catch (Exception ex)
        {
            return ex.Message;
        }
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM