- 1 year ago
How to enable "User must change the password at next logon" when creating a Local user account by c# application
To enable the "User must change the password at next logon" option when creating a local user account using a C# application, you can make use of the System.DirectoryServices.AccountManagement
namespace. Here's an example:
csharpusing System.DirectoryServices.AccountManagement;
public void CreateLocalUserAccount(string username, string password)
{
using (var context = new PrincipalContext(ContextType.Machine))
{
// Create a new UserPrincipal object
var user = new UserPrincipal(context);
user.SetPassword(password);
user.DisplayName = username;
user.Name = username;
user.UserCannotChangePassword = true;
user.PasswordNeverExpires = false;
user.Save();
}
}
In this example, the CreateLocalUserAccount
method creates a new local user account with the specified username
and password
. The UserPrincipal
class from the System.DirectoryServices.AccountManagement
namespace is used to interact with user accounts.
To enable the "User must change the password at next logon" option, we set the UserCannotChangePassword
property to true
. Note that we also set the PasswordNeverExpires
property to false
to ensure the password does expire at some point.
Make sure to add a reference to the System.DirectoryServices.AccountManagement
assembly to your project.
With this code, you should be able to create a local user account and enable the "User must change the password at next logon" option using a C# application.