title: .net : How to add a user to a Active Directory Security Group using C#?
body: <p>I am finding a reference to a security group to which I need to add user by using the following code:</p>
  
  <pre><code>string strActiveDirectoryPath = @"GC://domain.com";
  
  DirectoryEntry directoryEntryRoot = new DirectoryEntry(strActiveDirectoryPath);
  
  using (DirectorySearcher searcher = new DirectorySearcher(directoryEntryRoot))
  {  
      searcher.PageSize = 1000;
      searcher.Filter = "(&amp;(objectClass=group)(cn=*SGNAME*))";
      //searcher.SearchScope = SearchScope.Subtree;
      SearchResult securityGroup = searcher.FindOne();  
  }
  </code></pre>
  
  <p>The above code sometimes throws an exception saying </p>
  
  <blockquote>
    <p>Search resulted in too many records</p>
  </blockquote>
  
  <p>Is my logic of fetching the security group correct?</p>
  
  <p>Then I get reference to the user and try to add it to the security group:</p>
  
  <pre><code>searcher.Filter = "(SAMAccountName=" + UserAlias + ")";
  searcher.PropertiesToLoad.Add("givenname");
  searcher.PropertiesToLoad.Add("displayName");               
  
  SearchResult userALias = searcher.FindOne();
  
  DirectoryEntry ent = new DirectoryEntry(securityGroup.Path);              
  string domainString = "GC://domain.com/";
  int Start =  domainString.Length;
  string member = userALias.Path.Substring(domainString.Length);
  
  ent.Properties["member"].Add(member);
  // ent.Invoke("Add", new object[] { s });
  
  ent.CommitChanges();
  ent.Close();
  </code></pre>
  
  <p>I have created an instance of <code>DirectoryEntry</code> and provided a path of the security group that I have found.</p>
  
  <p>What should be provided to <code>DirectoryEntry</code>?</p>
  
  <p><code>CommitChanges</code> fails with exception: </p>
  
  <blockquote>
    <p>The server is unwilling to process the request.</p>
  </blockquote>
  
  <p><a href="https://i.stack.imgur.com/sW2TY.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/sW2TY.png" alt="enter image description here"></a></p>