In the snippet below, I will show you how to access the current users email address. As you begin to explore the Active Directory, remember that "mail" is only one of many attributes that you can accessed through LDAP. For more, go here. Happy Coding!! :)
You'll need to reference DirectoryServices in your project.
using System.DirectoryServices; using System.Security.Principal;
public static string DisplayEmail(IIdentity id) { string email = string.Empty; var winId = id as WindowsIdentity; if (id == null) { return "Identity is not a windows identity"; } var userInQuestion = winId.Name.Split('\\')[1]; var myDomain = winId.Name.Split('\\')[0]; var entry = new DirectoryEntry("LDAP://" + myDomain); var adSearcher = new DirectorySearcher(entry) { SearchScope = SearchScope.Subtree, Filter = "(&(objectClass=user)(samaccountname=" + userInQuestion + "))" }; var userObject = adSearcher.FindOne(); if (userObject != null) { email = string.Format("{0}", userObject.Properties["mail"][0]); } return email; }
Typically, I put functions like this in my Utility class but you can put it where ever you see fit. Below is an example of how to execute this function.
var email = Utility.DisplayUser(WindowsIdentity.GetCurrent());
No comments:
Post a Comment