[C#.NET][Active Directory] 使用 PrincipalSearcher 列舉 帳號 及 群組資訊
PrincipalSearcher 類別用來搜尋 AD 內的所有帳號及群組,這會用到以下兩個類別
- UserPrincipal:使用者資訊
- GroupPrincipal:群組資訊
{
this.listBox1.SelectedValueChanged += (s, obj) =>
{
ListBox box = (ListBox)s;
if (box.SelectedItem is UserPrincipal)
{
this.propertyGrid1.SelectedObject = (UserPrincipal)box.SelectedItem;
}
else if (box.SelectedItem is GroupPrincipal)
{
this.propertyGrid1.SelectedObject = (GroupPrincipal)box.SelectedItem;
}
};
}
搜尋所有使用者
{
this.listBox1.DataSource = null;
this.propertyGrid1.SelectedObject = null;
using (var context = new PrincipalContext(ContextType.Domain, this.textBox_Domain.Text, this.textBox_LoginUser.Text, this.textBox_LoginPassword.Text))
using (var user = new UserPrincipal(context))
using (var searcher = new PrincipalSearcher(user))
{
var results = searcher.FindAll().ToArray();
this.listBox1.DataSource = results;
}
}
執行結果如下:
搜尋所有群組
{
this.listBox1.DataSource = null;
this.propertyGrid1.SelectedObject = null;
using (var context = new PrincipalContext(ContextType.Domain, this.textBox_Domain.Text, this.textBox_LoginUser.Text, this.textBox_LoginPassword.Text))
using (var group = new GroupPrincipal(context))
using (var searcher = new PrincipalSearcher(group))
{
var results = searcher.FindAll().ToArray();
this.listBox1.DataSource = results;
}
}
執行結果如下:
以上內容出自:http://www.dotblogs.com.tw/yc421206/archive/2013/10/09/123487.aspx
若有謬誤,煩請告知,新手發帖請多包涵
Microsoft MVP Award 2010~2017 C# 第四季
Microsoft MVP Award 2018~2022 .NET