从Active Directory组中删除用户

时间:2014-02-23 07:01:31

标签: c# active-directory

我正在尝试使用C#从Active Directory组中删除某个用户。 这是我的代码片段应该处理我的任务,即使它当前不起作用。

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;
}

如果此代码中有任何拼写错误,请原谅我,我不得不从我正在开发的机器上手动复制它,遗憾地无法访问互联网。

2 个答案:

答案 0 :(得分:1)

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(); 

    }
}

答案 1 :(得分:0)

 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;
        }
    }
相关问题