Sunday, January 18, 2009

How To Delete An Active Directory User in c#

public void RemoveUserFromAD(string _UserName)
{

// Create a DirectorySearcher object using the user name as the LDAP search filter. If using a directory other than Exchange, use sAMAccountName instead of mailNickname.
DirectorySearcher searcher = new DirectorySearcher("(cn=" + _UserName + ")");

// Search for the specified user.
SearchResult result = searcher.FindOne();

// Make sure the user was found.

// Create a DirectoryEntry object to retrieve the collection of attributes (properties) for the user.
DirectoryEntry user = result.GetDirectoryEntry();

DirectoryEntry parentEntry = user.Parent;
parentEntry.Children.Remove(user);

searcher.Dispose();
result = null;
user.Close();
parentEntry.Close();

}

No comments: