C#操作 域AD 之登录、查询

版权声明:本博客系博主原创或转载,允许转载,但请保留原文出处。 https://blog.csdn.net/heivy/article/details/53505916

使用C#访问 Active Directory域服务,需引用System.DirectoryServices命名空间,该命名空间包含两个组件类,DirectoryEntry和 DirectorySearcher。

DirectoryEntry类可封装 ActiveDirectory域服务层次结构中的节点或对象,使用此类绑定到对象、读取属性和更新特性;
使用DirectorySearcher类可对 Active Directory域服务层次结构执行查询。
如果仅要对AD的组织单元,群组和用户进行查询或者更改属性,使用上述两个类即可。

下面给出操作AD域的部分代码:

1、连接到域

DirectoryEntry objDE = new DirectoryEntry(ADname, Loginname, Loginpwd);

ADname :是域名,一般格式是:"LDAP://****";****为域的名字(一般是大写的英文字符串)
Loginname: 登录域的用户名(保存在域中的名字,一般是中文名字的拼音)
Loginpwd: 用户名对应的登录密码

2、查询域中的所有用户

DirectoryEntry objDE = new DirectoryEntry(ADtxt, Logintxt, Loginpwdtxt);
string strFilter = "(&(objectCategory=person)(objectClass=user))";
DirectorySearcher objSearcher = new DirectorySearcher(objDE, strFilter);
//排序
objSearcher.Sort = new SortOption("name", SortDirection.Ascending);
SearchResultCollection src = objSearcher.FindAll();

src 中保存了所有用户的所有信息

如果想查找域中所有的组织单元,可以把筛选字符串改为:
string strFilter = "(&(objectCategory=organizationalUnit)(objectClass=organizationalUnit))";

如果想查找域中所有的群组,可以把筛选字符串改为:
string strFilter = "(&(objectCategory=group)(objectClass=group))";

2.1 查看用户的所有属性

//获取域用户属性
DirectoryEntry objDE = new DirectoryEntry(ADtxt, Logintxt, Loginpwdtxt);
string strFilter = "(&(objectCategory=person)(objectClass=user))";
DirectorySearcher objSearcher = new DirectorySearcher(objDE, strFilter);
//排序
objSearcher.Sort = new SortOption("name", SortDirection.Ascending);
SearchResultCollection src = objSearcher.FindAll()
DirectoryEntry entry = src[102].GetDirectoryEntry();
foreach (string pro in entry.Properties.PropertyNames)
{
this.tbLog.Text += entry.Properties[pro].PropertyName + ".........." + entry.Properties[pro].Value.ToString() + " \r\n";
}

或者:

foreach (string strPropNamein src[102].Properties.PropertyNames)
{
this.tbLog.Text +=strPropName;
}

2.2 查看用户的属性内容

foreach (SearchResult sr in src)
{
string chinesename = sr.Properties["name"][0].ToString();
string englishname= sr.Properties["samaccountname"][0].ToString();}

本文出自he ivy 的博客,转载请注明出处:http://blog.csdn.net/heivy/article/details/53505916

猜你喜欢

转载自blog.csdn.net/heivy/article/details/53505916