Home
Manage Your Code
Snippet: Get the Roles (Groups) A User Is A Member Of (C#)
Title: Get the Roles (Groups) A User Is A Member Of Language: C#
Description: Get all the role's that the user belongs to in the domain. Views: 132
Author: Kevin Shuma Date Added: 11/27/2007
Copy Code  
1/// <summary>

2		/// Get a user's active directory roles.

3		/// </summary>

4		/// <param name="DomainName">string.  The user's domain name.  Example "AMERICAS"</param>

5		/// <param name="UserName">string.  Active Directory user name.  Do not include the domain.  Example: "kevin_shuma"</param>

6		/// <returns>string array.  Listing of the user's Active Directory roles.</returns>

7		public static string[] RoleMemberships(string DomainName, string UserName)
8		{
9			try
10			{
11				string[] Roles = null;
12				//string Domain = (string)new DirectoryEntry("LDAP://RootDSE").Properties["defaultNamingContext"][0];

13				DirectoryEntry Entry = new DirectoryEntry("LDAP://" + DomainName);
14				DirectorySearcher Search = new DirectorySearcher(Entry);
15				Search.Filter = String.Format("(&(objectCategory=person)(samAccountName={0}))", UserName);
16				Search.PropertiesToLoad.Add("memberOf");
17				SearchResult Result = Search.FindOne();
18				if (Result != null)
19				{
20					Roles = new string[Result.Properties["memberOf"].Count];
21					for(int i = 0; i < Result.Properties["memberOf"].Count; i++)
22					{
23						string[] RoleDetails = Result.Properties["memberOf"][i].ToString().Split(',');
24						if (RoleDetails.Length > 0)
25						{
26							if (RoleDetails[0].IndexOf("CN=") != -1)
27								RoleDetails[0] = RoleDetails[0].Replace("CN=", "");
28							Roles[i] = RoleDetails[0];
29						}
30						else
31							Roles[i] = string.Empty;
32					}
33				}
34				else
35					throw new Exception("User not found in Active Directory.");
36				//Error = null;

37				return Roles;
38			}
39			catch (Exception ex)
40			{
41				//Error = ex;

42				Logging.LogException(MethodBase.GetCurrentMethod(), ref ex);
43				return null;
44			}
45		}