Top Stories Photos on Yahoo! News Photos

Wednesday, September 10, 2008

Get Active Directory User Name/Loging Name/Email in C#.NET

This code snippet is a continuing part of my existing post that has been posted in August 2008.Here I m explaining how to get User Login Name,User Actual Name,User Email Addresses and other active directory information using C#.In the example below I m extracting only user login name[UserPrincipalname] but all filter has been applied for your convince.You can replace any one as per your requirement.
You can also remove other filters that are not related to you.

DirectoryEntry de = GetDirectoryObject();
DirectorySearcher deSearch = new DirectorySearcher();
deSearch.SearchRoot = de;
int Count =0;
deSearch.Filter = "(&(objectClass=user))";
deSearch.SearchScope = SearchScope.Subtree;
deSearch.PropertiesToLoad.Add("cn"); // username
deSearch.PropertiesToLoad.Add("name"); // full name
deSearch.PropertiesToLoad.Add("givenname"); // firstname
deSearch.PropertiesToLoad.Add("sn"); // lastname
deSearch.PropertiesToLoad.Add("mail"); // mail
deSearch.PropertiesToLoad.Add("initials"); // initials
deSearch.PropertiesToLoad.Add("ou"); // organizational unit
deSearch.PropertiesToLoad.Add("userPrincipalName"); // login name
deSearch.PropertiesToLoad.Add("distinguishedName"); // distinguised nam

SearchResultCollection results = deSearch.FindAll();
//lstADUsers.Items.Clear();
if ((results != null))
{
foreach (System.DirectoryServices.SearchResult value in results)
{
Count++;
if (value.GetDirectoryEntry().Properties != null)
{
if (value.GetDirectoryEntry().Properties["sn"].Value != null)
{
if (value.GetDirectoryEntry().Properties["userPrincipalName"].Value != null)
{
string AdUsername = value.GetDirectoryEntry().Properties["userPrincipalName"].Value.ToString();
if (AdUsername.Length > 0)
{
if (AdUsername.Contains("@"))
AdUsername = AdUsername.Substring(0, AdUsername.IndexOf('@'));

lstADUsers.Items.Add(AdUsername);
if (Count % 2 == 0)
lblWait.Text = "PLEASE WAIT. ";
else
lblWait.Text = "PLEASE WAIT...";
Application.DoEvents();

}
}
}
}
}

}

//return arlUsers;

}

private DirectoryEntry GetDirectoryObject()
{
DirectoryEntry oDE;
oDE = new DirectoryEntry("LDAP://AD.LMKR.NET", @"DOMAINNAME\LOGINNAME", "PASSWORD", AuthenticationTypes.ReadonlyServer );
return oDE;
}

Like it or dislike it please comment....If you like it then forward this
Khuda Hafiz
Raja Imran Nisar

No comments: