我正在使用Windows窗体。我正在尝试显示Active Directory查询的结果 一个OU。所有用户和一组选择的属性。在此示例中,我仅使用email属性。我的问题分为三个部分。我真的很想回答第一部分。
我的代码如下:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.DirectoryServices.AccountManagement;
using System.DirectoryServices;
using AD_WinForm.hrlper;
using System.Data.Common;
namespace AD_WinForm
{
public partial class frmMain : Form
{
public frmMain()
{
InitializeComponent();
}
private void btnGet_Click(object sender, EventArgs e)
{
try {
string ou = THe distinguished name of OU;
using (PrincipalContext ctx = new PrincipalContext(ContextType.Domain,
Environment.UserDomainName, ou))
{
UserPrincipal user = new UserPrincipal(ctx);
using (PrincipalSearcher ps = new PrincipalSearcher(user))
{
//new code
DataTable results = new DataTable();
results.Columns.Add("mail");
// end new code
int count = 0;
foreach (Principal p in ps.FindAll())
{
UserPrincipal u = p as UserPrincipal;
if (u != null)
{
DirectoryEntry entry =
(DirectoryEntry)p.GetUnderlyingObject();
DirectorySearcher search = new DirectorySearcher(entry);
//UAC - (no disabled accounts or password never expires) and has a Email
//Account
string query = "(&(objectCategory=person)(objectClass=user)(!
(userAccountControl:1.2.840.113556.1.4.803:=2))(&(mail=*)))";
search.Filter = query;
search.PropertiesToLoad.Add("mail");
SearchResultCollection mySearchResultColl = search.FindAll();
//old code
//DataTable results = new DataTable();
//results.Columns.Add("mail");
//end old code
foreach (SearchResult sr in mySearchResultColl)
{
DataRow dr = results.NewRow();
DirectoryEntry de = sr.GetDirectoryEntry();
dr["mail"] = de.Properties["mail"].Value.ToString();
//dr["guid"] = de.Properties["guid"].Value;
results.Rows.Add(dr);
results.AcceptChanges();
count++;
}
DataView DV = new DataView(results);
dgvActiveDirectory.DataSource = DV;
}
}
lblCount.Text = count.ToString();
}
}
}
catch (NullReferenceException ex) {
MessageBox.Show(ex.ToString());
}
}
}
}