In this blog I wil show some easy codes to Create, and manipulate a local user account. In my code I will be utilising the WinNT provider.
Creating a local user account
string username = UserNameTextBox.Text; string password = PasswordTextBox.Text; try { DirectoryEntry localAd = new DirectoryEntry("WinNT://" + Environment.MachineName); DirectoryEntry user = localAd.Children.Add(username, "user"); user.Invoke("SetPassword", new object[] { password }); user.Invoke("Put", new object[] { "Description", password }); user.Invoke("Put", new object[] { "FullName", "You are " + username }); user.CommitChanges(); } catch (Exception ex) { MessageBox.Show(ex.Message); }
On this code I have shown a simple way to create a local user account. Here we user the Invoke to call a method thru reflection from the underlying WinNT provider.
Changing password
string username = UserNameTextBox.Text; string password = PasswordTextBox.Text; try { DirectoryEntry user = new DirectoryEntry("WinNT://" + Environment.MachineName + "/" + username); if (user != null) { user.Invoke("SetPassword", new object[] { password }); user.Invoke("Put", new object[] { "Description", password }); user.Invoke("Put", new object[] { "FullName", "You are " + username }); user.CommitChanges(); } } catch (Exception ex) { MessageBox.Show(ex.Message); }
This code is similar to the creation of user excep that the expression user from the provider is slightly different. Here we used the syntax WinNT://<server name>/<user name> to further filter our query toget the user name information. Alternatively, you can also implement the first code however you neede to use the Find function to get the user information.
Disabling an account
string username = UserNameTextBox.Text; string password = PasswordTextBox.Text; try { DirectoryEntry user = new DirectoryEntry("WinNT://" + Environment.MachineName + "/" + username); if (user != null) { user.Properties["UserFlags"].Value = Convert.ToInt32(user.Properties["UserFlags"].Value) | 2; user.CommitChanges(); } } catch (Exception ex) { MessageBox.Show(ex.Message); }
To disable a user account just user the “| 2″ expression against the existing value of the UserFlags. To enable it back just use the “& ~2″ expression against the existing value of the UserFlags (e.g. user.Properties["UserFlags"].Value = Convert.ToInt32(user.Properties["UserFlags"].Value) & ~2).
That’s it. Happy coding…