title: Having problems adding users to an Active Directory group using C#
body: <p>Okay, my problem right now is we're trying to write code that will add a user to a different group in our Active Directory. This is the solution we've written.</p>
  
  <p>Part of the main method:</p>
  
  <pre><code>string newGroup = "TestDelete";
  string userName = result.Properties["cn"][0].ToString();
  string adduser = ad.AddToGroup(userName, newGroup);
  Console.WriteLine(String.Format("{0} : {1}",userName, adduser)); 
  </code></pre>
  
  <p>Which calls this method from another class: </p>
  
  <pre><code>public String AddToGroup(string userDn, string groupDn)
  {
      try
      {
          DirectoryEntry ldapConnection = new DirectoryEntry("LDAP://OU=" + groupDn + ",DC=blah,DC=blah,DC=blah");
          ldapConnection.AuthenticationType = AuthenticationTypes.Secure;
  
          string newUser = "CN=" + userDn + "CN=Members,DC=blah,DC=blah,DC=blah";
  
          ldapConnection.Invoke("Add", new object[] { newUser });
          ldapConnection.CommitChanges();
          ldapConnection.Close();
  
          return "Success";
      }
      catch (System.DirectoryServices.DirectoryServicesCOMException E)
      {
          Console.WriteLine("Exception caught:\n\n" + E.ToString());
      }
  }
  </code></pre>
  
  <p>It's throwing the exception </p>
  
  <blockquote>
    <p><em>System.Runtime.InteropServices.COMException (0x80020006): Unknown name. (Exception from HRESULT: 0x80020006 (DISP_E_UNKNOWNNAME))<br>
    at System.DirectoryServices.DirectoryEntry.InvokeSet(String propertyName, Object[] args)<br>
    at adjustUsers.Program.AddToGroup(String userDn, String groupDn) in C:\Users\XXX\Documents\Visual Studio 2010\Projects\UserPruning\adjustUsers\Program.cs:line 45<br>
    at UserPruning.MainProgram.Main(String[] args) in C:\Users\XXX\Documents\Visual Studio 2010\Projects\UserPruning\UserPruning\MainProgram.cs:line 46</em></p>
  </blockquote>
  
  <p>Which, as far as we've been able to find indicates a problem with our syntax.</p>
  
  <p>Line 46 is  </p>
  
  <pre><code>string adduser = ad.AddToGroup(userName,newGroup)
  </code></pre>
  
  <p>Line 45 is  </p>
  
  <pre><code>ldapConnection.Invoke("Add", new object[] {newUser});
  </code></pre>
  
  <p>We've been trying to rewrite this piece of code for the last day and are still stumped. </p>
  
  <p>Help?</p>
  
  <p>Thanks</p>