小编典典

在.NET中的Active Directory组中添加和删除用户

c#

我正在编写以下方法,以从C#中的活动目录添加和删除用户。

void AddUserToGroup(string userId, string groupName);
void RemoveUserFromGroup(string userId, string groupName);

如何最好地实现这些方法?

这是CodeProject的一些代码。在这些示例中,我看不到在哪里指定AD服务器?(使用LDAP协议时,它是否由.NET框架隐式提供?)。这些例子值得关注吗?

public void AddToGroup(string userDn, string groupDn)
{
    try
    {
        DirectoryEntry dirEntry = new DirectoryEntry("LDAP://" + groupDn);
        dirEntry.Properties["member"].Add(userDn);
        dirEntry.CommitChanges();
        dirEntry.Close();
    }
    catch (System.DirectoryServices.DirectoryServicesCOMException E)
    {
        //doSomething with E.Message.ToString();

    }
}


public void RemoveUserFromGroup(string userDn, string groupDn)
{
    try
    {
        DirectoryEntry dirEntry = new DirectoryEntry("LDAP://" + groupDn);
        dirEntry.Properties["member"].Remove(userDn);
        dirEntry.CommitChanges();
        dirEntry.Close();
    }
    catch (System.DirectoryServices.DirectoryServicesCOMException E)
    {
        //doSomething with E.Message.ToString();

    }
}

阅读 517

收藏
2020-05-19

共1个答案

小编典典

啊。LDAP。如果您使用的是.Net Framework
3.5或更高版本,我强烈建议您使用System.DirectoryServices.AccountManagement命名空间。这使事情变得 如此
容易得多。

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

    } 
}

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

    }
}
2020-05-19