30 July 2004

Adding an Active Directory User [C#/.NET]

Posted by Mikhail Esteves under: Tips; Windows .

So how do we add an Active Directory User?

public string CreateADSUser(string username, string password, string homedir)
  {
      String RootDSE;

      try
      {
        if (!Directory.Exists(homedir))
          Directory.CreateDirectory(homedir);

        DirectorySearcher DSESearcher = new DirectorySearcher();
        RootDSE = DSESearcher.SearchRoot.Path;

        RootDSE = RootDSE.Insert(7, "CN=Users,");

        DirectoryEntry myDE = new DirectoryEntry(RootDSE);
        DirectoryEntries myEntries = myDE.Children;

        DirectoryEntry myDirectoryEntry = myEntries.Add("CN=" + username, "user");
        myDirectoryEntry.Properties["userPrincipalName"].Value = username;
        myDirectoryEntry.Properties["name"].Value = username;
        myDirectoryEntry.Properties["Password"].Value = password;
        myDirectoryEntry.Properties["samAccountName"].Value = username;
        myDirectoryEntry.Properties["FullName"].Value = username;
        myDirectoryEntry.Properties["AccountDisabled"].Value = 0;
        myDirectoryEntry.Properties["PasswordRequired"].Value = 1;
        myDirectoryEntry.Properties["HomeDirectory"].Value = homedir;

        // Permanent Password?
        myDirectoryEntry.Properties["permpass"].Value = 1;
        myDirectoryEntry.CommitChanges();

        DSESearcher.Dispose();
        myDirectoryEntry.Dispose();

        return "Worked!";
      }
      catch (Exception ex)
      {
        return ex.Message;
      }
  }

[update] Just found a class by Craig Aroa called ADHelper . It lets you do all this and more.



4 Comments so far...

Martin Selae Says:

31 January 2006 at 12:18 pm.

It’s work TNX !

hahaha Says:

2 March 2007 at 4:37 pm.

it’s work-ING

Tom Says:

7 August 2007 at 11:37 am.

Cool, or you could use the A.D. Advantage c# library (ad-advantage.net) to do all that with a single line of code.

Emad Bsty Says:

18 September 2007 at 10:24 am.

Thanks For Your Efforts ?

Leave a Reply

Browse

Photography

Projects

Pages

Calendar

July 2004
M T W T F S S
« Jun   Aug »
 1234
567891011
12131415161718
19202122232425
262728293031  

Categories

www.flickr.com

Use OpenDNS