How to change password for user account using C # code?

how to change password on user account using c # code?

+5
source share
3 answers

Using the active directory:

// Connect to Active Directory and get the DirectoryEntry object.
// Note, ADPath is an Active Directory path pointing to a user. You would have created this
// path by calling a GetUser() function, which searches AD for the specified user
// and returns its DirectoryEntry object or path. See http://www.primaryobjects.com/CMS/Article61.aspx
DirectoryEntry oDE;
oDE = new DirectoryEntry(ADPath, ADUser, ADPassword, AuthenticationTypes.Secure);

try
{
   // Change the password.
   oDE.Invoke("ChangePassword", new object[]{strOldPassword, strNewPassword});
} 
catch (Exception excep)
{
   Debug.WriteLine("Error changing password. Reason: " + excep.Message);
}

Here you have an example to change it in the local user account:

http://msdn.microsoft.com/en-us/library/ms817839

Another alternative would be to use interoperability and calling unmanaged code: netapi32.dll

http://msdn.microsoft.com/en-us/library/aa370650(VS.85).aspx

+5
source

Here is an easier way to do this, however you will need to refer to System.DirectoryServices.AccountManagement from .Net 4.0

namespace PasswordChanger
{
    using System;
    using System.DirectoryServices.AccountManagement;

    class Program
    {
        static void Main(string[] args)
        {
            ChangePassword("domain", "user", "oldpassword", "newpassword");
        }

        public static void ChangePassword(string domain, string userName, string oldPassword, string newPassword)
        {
            try
            {
                using (var context = new PrincipalContext(ContextType.Domain, domain))
                using (var user = UserPrincipal.FindByIdentity(context, IdentityType.SamAccountName, userName))
                {
                    user.ChangePassword(oldPassword, newPassword);
                }

            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);
            }
        }
    }
}
+4
source
        DirectoryEntry AD = new DirectoryEntry("WinNT://" + Environment.MachineName + ",computer");
        DirectoryEntry grp;
        grp = AD.Children.Find("test", "user");
        if (grp != null)
        {
            grp.Invoke("SetPassword", new object[] { "test" });
        }
        grp.CommitChanges();
        MessageBox.Show("Account Change password Successfully");

"run admin to change all users

+1
source

All Articles