using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.DirectoryServices;
/// <summary>
///ADUtil 的摘要说明
/// </summary>
public class ADUtil
{
// LDAP地址 例如:LDAP://my.com.cn
private const string LDAP_HOST = "LDAP://my.com.cn";
// 具有LDAP管理权限的特殊帐号
private const string USER_NAME = "account";
// 具有LDAP管理权限的特殊帐号的密码
private const string PASSWORD = "password";
public ADUtil()
{
//
//TODO: 在此处添加构造函数逻辑
//
}
/**
* 向某个组添加人员
* groupName 组名称
* userName 人员域帐号
**/
public static void addGroupMember(string groupName, string userName)
{
DirectoryEntry group = getGroupByName(groupName);
group.Username = USER_NAME;
group.Password = PASSWORD;
group.Properties["member"].Add(getUserDNByName(userName));
group.CommitChanges();
}
/**
* 从某个组移出指定的人员
* groupName 组名称
* userName 人员域帐号
**/
public static void removeGroupMember(string groupName, string userName)
{
DirectoryEntry group = getGroupByName(groupName);
group.Username = USER_NAME;
group.Password = PASSWORD;
group.Properties["member"].Remove(getUserDNByName(userName));
group.CommitChanges();
}
/**
* 获取指定人员的域信息
* name 人员域帐号
**/
public static object getUserDNByName(string name)
{
DirectorySearcher userSearch = new DirectorySearcher(LDAP_HOST);
userSearch.SearchRoot = new DirectoryEntry(LDAP_HOST, USER_NAME, PASSWORD);
userSearch.Filter = "(SAMAccountName=" + name + ")";
SearchResult user = userSearch.FindOne();
if (user == null)
{
throw new Exception("请确认域用户是否正确");
}
return user.Properties["distinguishedname"][0];
}
/**
* 获取指定域组的信息
* name 组名称
**/
public static DirectoryEntry getGroupByName(string name)
{
DirectorySearcher search = new DirectorySearcher(LDAP_HOST);
search.SearchRoot = new DirectoryEntry(LDAP_HOST, USER_NAME, PASSWORD);
search.Filter = "(&(cn=" + name + ")(objectClass=group))";
search.PropertiesToLoad.Add("objectClass");
SearchResult result = search.FindOne();
DirectoryEntry group;
if (result != null)
{
group = result.GetDirectoryEntry();
}
else {
throw new Exception("请确认AD组列表是否正确");
}
return group;
}
}