title: Create Active Directory user in .NET (C#)
body: <p>I need to create a new user in Active Directory. I have found several examples like the following:</p>
  
  <pre><code>using System;
  using System.DirectoryServices;
  
  namespace test {
     class Program {
        static void Main(string[] args) {
          try {
              string path = "LDAP://OU=x,DC=y,DC=com";
              string username = "johndoe";
  
              using (DirectoryEntry ou = new DirectoryEntry(path)) {
                 DirectoryEntry user = ou.Children.Add("CN=" + username, "user");
  
                 user.Properties["sAMAccountName"].Add(username);
  
                 ou.CommitChanges();
              }
           } 
           catch (Exception exc) {
               Console.WriteLine(exc.Message);
           }
        }
     }
  }
  </code></pre>
  
  <p>When I run this code I get no errors, but no new user is created. </p>
  
  <p>The account I'm running the test with has sufficient privileges to create a user in the target Organizational Unit.  </p>
  
  <p>Am I missing something (possibly some required attribute of the user object)?</p>
  
  <p>Any ideas why the code does not give exceptions?</p>
  
  <p><strong>EDIT</strong><br>
  The following worked for me:</p>
  
  <pre><code>int NORMAL_ACCOUNT = 0x200;
  int PWD_NOTREQD = 0x20;
  DirectoryEntry user = ou.Children.Add("CN=" + username, "user");
  user.Properties["sAMAccountName"].Value = username;
  user.Properties["userAccountControl"].Value = NORMAL_ACCOUNT | PWD_NOTREQD;
  user.CommitChanges();
  </code></pre>
  
  <p>So there were actually a couple of problems:</p>
  
  <ol>
  <li><code>CommitChanges</code> must be called on <code>user</code> (thanks Rob)</li>
  <li>The password policy was preventing the user to be created (thanks Marc)</li>
  </ol>