Copy codeThe Code is as follows: using System;
Using System. Collections. Generic;
Using System. Linq;
Using System. Text;
Using System. DirectoryServices;
Namespace authentication. Framework. Security
{
///
/// Computer users and group operations
///
Public class UserAndGroupHelper
{
Private static readonly string PATH = "WinNT: //" + Environment. MachineName;
///
/// Add a windows User
///
/// User Name
/// Password
/// Group
/// Description
Public static void AddUser (string username, string password, string group, string description)
{
Using (DirectoryEntry dir = new DirectoryEntry (PATH ))
{
Using (DirectoryEntry user = dir. Children. Add (username, "User") // Add a user name
{
User. Properties ["FullName"]. Add (username); // full name of the user
User. Invoke ("SetPassword", password); // user password
User. Invoke ("Put", "Description", description); // detailed user Description
// User. Invoke ("Put", "PasswordExpired", 1); // you need to change the password for the next login
User. Invoke ("Put", "UserFlags", 66049); // The password never expires.
// User. Invoke ("Put", "UserFlags", 0x0040); // the user cannot change the password s
User. CommitChanges (); // Save the user
Using (DirectoryEntry grp = dir. Children. Find (group, "group "))
{
If (grp. Name! = "")
{
Grp. Invoke ("Add", user. Path. ToString (); // Add a user to a group
}
}
}
}
}
///
/// Change the password of a windows User
///
/// User Name
/// New Password
Public static void UpdateUserPassword (string username, string newpassword)
{
Using (DirectoryEntry dir = new DirectoryEntry (PATH ))
{
Using (DirectoryEntry user = dir. Children. Find (username, "user "))
{
User. Invoke ("SetPassword", new object [] {newpassword });
User. CommitChanges ();
}
}
}
///
/// Delete a windows User
///
/// User Name
Public static void RemoveUser (string username)
{
Using (DirectoryEntry dir = new DirectoryEntry (PATH ))
{
Using (DirectoryEntry user = dir. Children. Find (username, "User "))
{
Dir. Children. Remove (user );
}
}
}
///
/// Add a windows User Group
///
/// Group name
/// Description
Public static void AddGroup (string groupName, string description)
{
Using (DirectoryEntry dir = new DirectoryEntry (PATH ))
{
Using (DirectoryEntry group = dir. Children. Add (groupName, "group "))
{
Group. Invoke ("Put", new object [] {"Description", description });
Group. CommitChanges ();
}
}
}
///
/// Delete the windows User Group
///
/// Group name
Public static void RemoveGroup (string groupName)
{
Using (DirectoryEntry dir = new DirectoryEntry (PATH ))
{
Using (DirectoryEntry group = dir. Children. Find (groupName, "Group "))
{
Dir. Children. Remove (group );
}
}
}
}
}