前一段时间做了一个从SHR系统 同步用户、组织的小程序,现在分享给大家;
废话不多说,直接上代码。
首先引用:using System.DirectoryServices;
定义基本连接属性:
private string RootPath = "OU=TestOU,DC=ittest,DC=com"; //根路径
private string ADPath = "LDAP://10.10.9.230/" ; //主机地址
private string ADUser = "sunlizhen"; //登录账户
//AD管理员密码
private string ADPasssWord = "abc123";//密码
获取DirectoryEntry 对象
private DirectoryEntry GetDirectoryObject(string path ="")
{
//path LDAP://10.10.9.230/OU=TestOU,DC=ittest,DC=com
DirectoryEntry entry = null;
try
{ if (path == "")
{
entry = new DirectoryEntry(ADPath + RootPath, ADUser, ADPasssWord, AuthenticationTypes.Secure);
}
else
{
entry = new DirectoryEntry(path, ADUser, ADPasssWord, AuthenticationTypes.Secure);
string newguid = entry.Guid.ToString();
}
}
catch (Exception ex)
{
entry = null;
}
return entry;
}
获取用户对象
/// <summary>
/// 根据用户公共名称取得用户的 对象
/// </summary>
/// <param name="commonName">用户公共名称</param>
/// <returns>如果找到该用户则返回用户的对象,否则返回 null</returns>
public DirectoryEntry GetUserEntry(string commonName)
{
DirectoryEntry de = GetDirectoryObject();
DirectorySearcher deSearch = new DirectorySearcher(de);
deSearch.Filter = "(&(&(objectCategory=person)(objectClass=user))(cn=" + commonName.Replace("\\", "") + "))";
deSearch.SearchScope = SearchScope.Subtree;
try
{
SearchResult result = deSearch.FindOne();
if (result == null)
return null;
//de = new DirectoryEntry(result.Path);
de = GetDirectoryObject(result.Path);
return de;
}
catch (Exception ex)
{
return null;
}
}
获取组织对象
/// <summary>
// 获取组织单位
/// </summary>
/// <param name="ouname">组织名称</param>
/// <returns></returns>
public DirectoryEntry GetOU(string ouname)
{
DirectorySearcher deSearch = new DirectorySearcher();
deSearch.Filter = string.Format("(&(objectClass=organizationalUnit) (OU={0}))", ouname);
SearchResult results = deSearch.FindOne();
if (results != null)
{
return results.GetDirectoryEntry();
}
else
{
return null;
}
}
获取group对象
/// <summary>
/// 根据组名获取组织对象
/// </summary>
/// <param name="commonName">组名</param>
/// <returns>如果找到该用户则返回用户的对象,否则返回 null</returns>
public DirectoryEntry GetGroupEntry(string commonName)
{
DirectoryEntry de = GetDirectoryObject();
DirectorySearcher deSearch = new DirectorySearcher(de);
deSearch.Filter = "(&(objectClass=group)(cn=" + commonName + "))";
deSearch.SearchScope = SearchScope.Subtree;
try
{
SearchResult result = deSearch.FindOne();
if (result == null)
return null;
// de = new DirectoryEntry(result.Path);
de = GetDirectoryObject(result.Path);
return de;
}
c