If you are using .NET 3.5 or higher, you can use the new System.DirectoryServices.AccountManagement (S.DS.AM) namespace, which makes this a lot easier than before.
Read more about this here: Guide for Security Managers in the .NET Framework 3.5
Update: old MSDN magazine articles are no longer online, you unfortunately need to download the CHM for January 2008 Microsoft's MSDN magazine and read the article there.
Basically, you need to have a โmain contextโ (usually your domain), a user principle, and then you easily get its groups:
public List<GroupPrincipal> GetGroups(string userName) { List<GroupPrincipal> result = new List<GroupPrincipal>(); // establish domain context PrincipalContext yourDomain = new PrincipalContext(ContextType.Domain); // find your user UserPrincipal user = UserPrincipal.FindByIdentity(yourDomain, userName); // if found - grab its groups if(user != null) { PrincipalSearchResult<Principal> groups = user.GetAuthorizationGroups(); // iterate over all groups foreach(Principal p in groups) { // make sure to add only group principals if(p is GroupPrincipal) { result.Add((GroupPrincipal)p); } } } return result; }
and that everything is there! Now you have the result (list) of authorization groups to which the user belongs - sort them, print their names or whatever you need to do.
Update. To access certain properties that are not displayed on the UserPrincipal object, you need to search the underlying DirectoryEntry :
public string GetDepartment(Principal principal) { string result = string.Empty; DirectoryEntry de = (principal.GetUnderlyingObject() as DirectoryEntry); if (de != null) { if (de.Properties.Contains("department")) { result = de.Properties["department"][0].ToString(); } } return result; }
Update # 2: It doesn't seem to be too hard to put these two pieces of code together ... but fine - here it is:
public string GetDepartment(string username) { string result = string.Empty; // if you do repeated domain access, you might want to do this *once* outside this method, // and pass it in as a second parameter! PrincipalContext yourDomain = new PrincipalContext(ContextType.Domain); // find the user UserPrincipal user = UserPrincipal.FindByIdentity(yourDomain, username); // if user is found if(user != null) { // get DirectoryEntry underlying it DirectoryEntry de = (user.GetUnderlyingObject() as DirectoryEntry); if (de != null) { if (de.Properties.Contains("department")) { result = de.Properties["department"][0].ToString(); } } } return result; }
marc_s Mar 15 '11 at 10:22 2011-03-15 10:22
source share