title: Adding and removing users from Active Directory groups in .NET
body: <p>I am writing the following methods to add and remove users from active directory in C#.</p>
  
  <pre><code>void AddUserToGroup(string userId, string groupName);
  void RemoveUserFromGroup(string userId, string groupName);
  </code></pre>
  
  <p>How best to implement these methods?</p>
  
  <p>Here is some code from CodeProject. I can't see where the AD server is specified in these examples though? (is it implicitly supplied by the .NET framework when using the LDAP protocol?). Are these examples worth following?</p>
  
  <pre><code>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();
  
      }
  }
  </code></pre>