9

how to change password to user account, by c# code?

codingbadger
  • 42,678
  • 13
  • 95
  • 110
sari k
  • 2,051
  • 6
  • 28
  • 34

4 Answers4

9

Here is a simpler way to do this, however you will need to reference 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);
            }
        }
    }
}
Paul
  • 1,011
  • 10
  • 13
  • 2
    Works great even without admin privileges, thanks Paul. – mberna May 25 '17 at 15:09
  • I got an exception AccessDenied even when I ran the app as administrator. I ended up using the solution here: https://stackoverflow.com/questions/7567701/system-unauthorizedaccessexception-calling-userprincipal-setpassword – boggy May 29 '20 at 23:40
5

Using 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 example to change it in the local user account:

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

Other alternative could be using interoperability and call unmanaged code: netapi32.dll

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

Daniel Peñalba
  • 30,507
  • 32
  • 137
  • 219
  • Thanks for your help, how can I get ADPath? need to use with ActiveDS, If so, how? – sari k Nov 23 '10 at 08:45
  • Sorry, the link on the code is hidden, maybe stack overflow could improve this :-) Here is the link to the general use of AD and how to build the ADPath: http://www.primaryobjects.com/CMS/Article61.aspx – Daniel Peñalba Nov 23 '10 at 09:07
1
        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 in administrator to change all user

Programer_saeed
  • 133
  • 2
  • 5
0

This works for both AD and Local Accounts.

If you want to invoke this API via C#, you may use this signature to import API NetUserChangePassword to your C# code:

[DllImport("netapi32.dll", CharSet=CharSet.Unicode, CallingConvention=CallingConvention.StdCall,SetLastError=true )]
static extern uint NetUserChangePassword (

[MarshalAs(UnmanagedType.LPWStr)] string domainname,

[MarshalAs(UnmanagedType.LPWStr)] string username,

[MarshalAs(UnmanagedType.LPWStr)] string oldpassword,

[MarshalAs(UnmanagedType.LPWStr)] string newpassword);
Mihai Chelaru
  • 7,614
  • 14
  • 45
  • 51
Scott Jasin
  • 117
  • 6