M
Matt
Does anyone have an example of querying Active Directory
using ADO.NET from C#? I am trying to populate a
DataTable with first name, last name and email address
but whenever I try to do this using DirectoryServices I
get an error "Object reference not set to an instance of
an object". Code as follows:
DataTable dt = new DataTable("Addresses");
dt.Columns.Add(new DataColumn("LastName",
System.Type.GetType("System.String")));
dt.Columns.Add(new DataColumn("FirstName",
System.Type.GetType("System.String")));
dt.Columns.Add(new DataColumn("Email",
System.Type.GetType("System.String")));
DirectoryEntry entry = new DirectoryEntry("MYDOMAIN.COM");
DirectorySearcher mySearcher = new
System.DirectoryServices.DirectorySearcher(entry);
mySearcher.PropertyNamesOnly = true;
mySearcher.PropertiesToLoad.Add("givenName");
mySearcher.PropertiesToLoad.Add("sn");
mySearcher.PropertiesToLoad.Add("mail");
mySearcher.Filter = ("(ObjectClass=user)");
foreach(SearchResult resEnt in mySearcher.FindAll())
{
DirectoryEntry de = resEnt.GetDirectoryEntry();
DataRow nr = dt.NewRow();
nr["LastName"] = de.Properties
["givenName"].Value.ToString();
nr["FirstName"] = de.Properties
["sn"].Value.ToString();
nr["Email"] = de.Properties["mail"].Value.ToString
();
dt.Rows.Add(nr);
}
using ADO.NET from C#? I am trying to populate a
DataTable with first name, last name and email address
but whenever I try to do this using DirectoryServices I
get an error "Object reference not set to an instance of
an object". Code as follows:
DataTable dt = new DataTable("Addresses");
dt.Columns.Add(new DataColumn("LastName",
System.Type.GetType("System.String")));
dt.Columns.Add(new DataColumn("FirstName",
System.Type.GetType("System.String")));
dt.Columns.Add(new DataColumn("Email",
System.Type.GetType("System.String")));
DirectoryEntry entry = new DirectoryEntry("MYDOMAIN.COM");
DirectorySearcher mySearcher = new
System.DirectoryServices.DirectorySearcher(entry);
mySearcher.PropertyNamesOnly = true;
mySearcher.PropertiesToLoad.Add("givenName");
mySearcher.PropertiesToLoad.Add("sn");
mySearcher.PropertiesToLoad.Add("mail");
mySearcher.Filter = ("(ObjectClass=user)");
foreach(SearchResult resEnt in mySearcher.FindAll())
{
DirectoryEntry de = resEnt.GetDirectoryEntry();
DataRow nr = dt.NewRow();
nr["LastName"] = de.Properties
["givenName"].Value.ToString();
nr["FirstName"] = de.Properties
["sn"].Value.ToString();
nr["Email"] = de.Properties["mail"].Value.ToString
();
dt.Rows.Add(nr);
}