代碼如下:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.DirectoryServices;
namespace JH.Framework.Security
{
///
/// 計算機用戶和組操作類
///
public class UserAndGroupHelper
{
private static readonly string PATH = "WinNT://" + Environment.MachineName;
///
/// 添加windows用戶
///
/// 用戶名
/// 密碼
/// 所屬組
/// 描述
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")) //增加用戶名
{
user.Properties["FullName"].Add(username); //用戶全稱
user.Invoke("SetPassword", password); //用戶密碼
user.Invoke("Put", "Description", description);//用戶詳細描述
//user.Invoke("Put","PasswordExpired",1); //用戶下次登錄需更改密碼
user.Invoke("Put", "UserFlags", 66049); //密碼永不過期
//user.Invoke("Put", "UserFlags", 0x0040);//用戶不能更改密碼s
user.CommitChanges();//保存用戶
using (DirectoryEntry grp = dir.Children.Find(group, "group"))
{
if (grp.Name != "")
{
grp.Invoke("Add", user.Path.ToString());//將用戶添加到某組
}
}
}
}
}
///
/// 更改windows用戶密碼
///
/// 用戶名
/// 新密碼
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();
}
}
}
///
/// 刪除windows用戶
///
/// 用戶名
public static void RemoveUser(string username)
{
using (DirectoryEntry dir = new DirectoryEntry(PATH))
{
using (DirectoryEntry user = dir.Children.Find(username, "User"))
{
dir.Children.Remove(user);
}
}
}
///
/// 添加windows用戶組
///
/// 組名稱
/// 描述
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();
}
}
}
///
/// 刪除windows用戶組
///
/// 組名稱
public static void RemoveGroup(string groupName)
{
using (DirectoryEntry dir = new DirectoryEntry(PATH))
{
using (DirectoryEntry group = dir.Children.Find(groupName, "Group"))
{
dir.Children.Remove(group);
}
}
}
}
}