How To Change a User Password with C# and Active Directory

It took me a little digging around to get this code right: whatever I was doing wrong with the LDAP path / DirectoryServices instantiation was giving me a "Error Code 8007202B - A referral was returned from the server". This is just a sample -- any real world use of this should obviously have better error handling and some unit tests built in.
using System;
using System.DirectoryServices;

class Testclass
{
	static void Main()
	{
		string userName = "Bob";
		string oldPassword = "123shoot"
		string newPassword = "KJ#$#H";

		Console.WriteLine("changing password for " + userName + " from "  
					+ oldPassword + " to " + newPassword);

		ChangePassword(userName, oldPassword, newPassword);

	}

	public static void ChangePassword(string userName, string oldPassword, string newPassword)
	{
		string path = "LDAP://CN=" + userName + ",CN=Users,DC=demo,DC=domain,DC=com";

		//Instantiate a new DirectoryEntry using an administrator uid/pwd
		//In real life, you'd store the admin uid/pwd  elsewhere
		DirectoryEntry directoryEntry = new DirectoryEntry(path, "administrator", "password");

		try
		{
		   directoryEntry.Invoke("ChangePassword", new object[]{oldPassword, newPassword});
		}
		catch (Exception ex)  //TODO: catch a specific exception ! :)
		{
		   Console.WriteLine(ex.Message);
		}

		Console.WriteLine("success");
	}
}


17 August Update: in response to a question about this code, be sure you have the System.DirectoryServices reference:

Categories

,
| Comments (1)TrackBacks (0)

0 TrackBacks

Listed below are links to blogs that reference this entry: How To Change a User Password with C# and Active Directory.

TrackBack URL for this entry: http://www.rootsilver.com/mt-tb.cgi/11

1 Comments

shashi said:

does this mean you have to create the directoryEntry object with the admin userid/pw

but it can change the password for another user..when you use the DirectoryEntry.Invoke("ChangePassword", new object[]{oldPassword, newPassword});

??


************************************************
DirectoryEntry directoryEntry = new DirectoryEntry(path, "administrator", "password");

try
{
directoryEntry.Invoke("ChangePassword", new object[]{oldPassword, newPassword});
}

*********************

Leave a comment