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

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();
}

2 comments:

Jason said...

Kyle great article about adsi! BTW do you have any good movie recommendation? Middle men was great!

Dharik said...

Hey Kyle what are your thoughts on structural typing? The hip new languages golang and typescript do this and it looks like a nice design


Btw jason - scott is coming to cali next year and we’re planning a hiking camping napa trip. You shoukd join

About Me

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