How to rename an user in Active Directory with C#

 

If you want to rename an user in Active Directory by using C#, you can use the following code:

using System;
using System.Collections.Generic;
using System.DirectoryServices;
using System.DirectoryServices.AccountManagement;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
try
{
Console.WriteLine("This application will rename a user in active directory.");
Console.WriteLine(Environment.NewLine);
Console.WriteLine("Enter domain:");
string domain = Console.ReadLine();
Console.WriteLine("Connecting to domaincontroller.");
using (PrincipalContext context = new PrincipalContext(ContextType.Domain, domain))
{
if (context == null)
{
throw new ApplicationException("Domain not found.");
}
Console.WriteLine("Enter current username (e.g. john):");
string currentUserName = Console.ReadLine();
using (UserPrincipal user = UserPrincipal.FindByIdentity(context, currentUserName))
{
if (user == null)
{
throw new ApplicationException("User not found.");
}
Console.WriteLine("Enter new username (e.g. john2):");
string newUserName = Console.ReadLine();
using (DirectoryEntry entry = (DirectoryEntry)user.GetUnderlyingObject())
{
Console.WriteLine("Setting account properties in active directory.");
entry.InvokeSet("uid", newUserName);
entry.InvokeSet("sAMAccountName", newUserName);
entry.InvokeSet("userPrincipalName", string.Format("{0}@{1}", newUserName, domain));
entry.CommitChanges();
Console.WriteLine("Rename common-name (CN).");
entry.Rename("CN=" + newUserName);
entry.CommitChanges();
Console.WriteLine("User successfully renamed.");
}
}
}
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
}
Console.WriteLine("Press enter to continue...");
Console.ReadLine();
}
}
}

Leave a Reply

Your email address will not be published. Required fields are marked *

2 comments

  1. Marc says:

    och roel…
    http://technet.microsoft.com/nl-nl/library/ee617225.aspx

    rename-adobject 🙂 much faster

  2. faizal says:

    Hi, I am getting error like below

    An exception of type ‘System.UnauthorizedAccessException’ occurred in System.DirectoryServices.dll but was not handled in user code.

    How to check the user authorization.