複製代碼 代碼如下: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);
}
}
}
}
}