Adding and removing users from Active Directory groups in .NET

前端 未结 4 741
野趣味
野趣味 2020-11-29 00:14

I am writing the following methods to add and remove users from active directory in C#.

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


        
相关标签:
4条回答
  • 2020-11-29 00:44

    Ugh. LDAP. If you're using the .Net Framework 3.5 or above, I highly recommend using the System.DirectoryServices.AccountManagement namespace. That makes things so much easier.

    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(); 
    
        }
    }
    
    0 讨论(0)
  • 2020-11-29 00:49

    The server is part of the groupDn variable value. For example:

    LDAP://myServer/CN=MyGroup,CN=Groups,CN=MyContainer,DN=mydomain.com

    The whole thing is the LDAP path for the group. The first part (myServer) is the server name.

    The part after the server name (e.g. CN=...) is the DN (distinguished name) of the group.

    0 讨论(0)
  • 2020-11-29 00:52

    You can put the LDAP server in the path argument to DirectoryEntry, so "LDAP://" + ldapServer + ldapQuery.

    Use the DirectoryEntry(String path, String userId, String password) if you need to authenticate

    0 讨论(0)
  • 2020-11-29 00:58

    When deleting a member in public void RemoveUserFromGroup(string userDn, string groupDn)

    dirEntry.Properties["member"].Remove(userDn) does not work for me.

    dirEntry.Properties["member"].RemoveAt(dn.IndexOf(dn)) works.

    0 讨论(0)
提交回复
热议问题