Tips, tricks, and frustrations from my years of building ASP.NET websites.

Showing posts with label IADsUser. Show all posts
Showing posts with label IADsUser. Show all posts

Monday, April 21, 2008

List the groups for the specified user in C# using ADSI.

Using the ADSI IADsUser class and it's 'Groups' method to get a list of groups of which the user is a member is fairly simple once you know the trick.

First, you will have to add a reference to the 'Active Directory DS' COM object.
Second, add the statement: using ActiveDS;

Here is a GroupNames() function to demo the process:

using ActiveDS;

public static string[] GroupNames(string userName)
{
   List result = new List(20);
   if (String.IsNullOrEmpty(userName) == true)
   {
      return null;
   }


   userName = userName.Trim().Replace('\\', '/');


   DirectoryEntry de = new DirectoryEntry(String.Format("WinNT://{0},user", userName));


   IADsMembers groupsForUser = (IADsMembers) de.Invoke("Groups",null);


   foreach (object group in groupsForUser)
   {
      DirectoryEntry deGroup = new DirectoryEntry(group);
      result.Add(deGroup.Name);
   }


   if (result.Count == 0)
   {
      return null;
   }
   
   return result.ToArray();
}

About Me

I'm currently employed as a Senior Systems Programmer/Analyst and sometimes Project Manager at Texas Instruments Inc. in Plano TX.