Monday, January 26, 2015

Change Password of a (local) Windows User Account

In this post I want to show, how one can change the password of a Windows user using C#.
For this there are multiple possibilities, here we use the class PrincipalContext.
Using this, but also the other methods, in Windows 8 it is important that the type of user account is set to local (can be changed), and not to Windows account.
In the project we add a reference to the assembly System.DirectoryServices.AccountManagement, and with the following short code the password of a user can be changed:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

using System.DirectoryServices.AccountManagement;

namespace ChangePW
    public partial class Form1 : Form
        public Form1()

        private void Form1_Load(object sender, EventArgs e)
                var Context = new PrincipalContext(ContextType.Machine);
                var User = UserPrincipal.FindByIdentity(Context, IdentityType.SamAccountName, username);
                User.ChangePassword(oldPassword, newPassword);

As one can see, we first create a PrincipalContext object. ContextType.Machine determines, that we want to access the local computer. From this we then select the desired user, and change its password.

1 comment:

  1. Want to learn C# from basics & in most professional Code development style. I'll have you writing real working applications in no time flat-before you reach the end of course.
    Hire C# Teacher.