The companion files include a more complex sample application. It is a console application that can expose the groups that a computer or a user is a member of. This code shows a number of techniques for using the DirectoryServices library. First is the use of the schemafilter property, which allows you to filter containers based on schemas of objects in the container. Second is the use of the Invoke method to call a native method on Active Directory. Here is the code from the sample application:
using System; using System.DirectoryServices; using System.Reflection; using System.Collections; namespace ADSI_Console_App { /// <summary> /// Summary description for Class1. /// </summary> class Class1 { /// <summary> /// The main entry point for the application. /// </summary> [STAThread] static void Main(string[] args) { try { //Replace thomriznt5dom2 with your domain GroupsMembers("WinNT://thomriznt5dom2/thomriznt52,computer"); // groups in computer UserGroups("LDAP:// CN=Thomas Rizzo,CN=Users,DC=thomriznt5dom2,DC=extest,DC=microsoft,DC=com"); // local groups member UserGroups("WinNT://thomriznt5dom2/thomriz,user"); // local groups member } catch (Exception e) { Console.WriteLine("*** Exception: " + e); } return; } // ---------------------------------------- // Get all members for groups in given root. static void GroupsMembers(string root_name) { Console.WriteLine(""); Console.WriteLine(" --- Groups Members in: " + root_name); DirectoryEntry entryMachine = new DirectoryEntry(root_name); entryMachine.Children.SchemaFilter.Add("group"); int kg = 0; foreach ( DirectoryEntry grp in entryMachine.Children ) { Console.WriteLine("group: " + grp.Name); object members = grp.Invoke("Members"); // IADsGroup method call if ( ++kg > 12 ) break; // stop long output foreach ( object member in (IEnumerable)members) { try { DirectoryEntry memberEntry = new DirectoryEntry(member); // 'member' is an IAds ptr object Console.WriteLine(" member = " + memberEntry .Name); } catch (System.Runtime.InteropServices.COMException e) { Console.WriteLine(" !!! Bad Member. Hr: 0x" + Convert.ToString(e.ErrorCode,16) + " - " + e.Message); } } } Console.WriteLine("----"); } // ---------------------------------------- // Get all groups which a user is member of. static void UserGroups(string user_name) { Console.WriteLine(""); Console.WriteLine("--- User: " + user_name + " is the member of: "); DirectoryEntry entryUser = new DirectoryEntry(user_name); object groups = entryUser.Invoke("Groups"); // IADsUser method call foreach ( object group in (IEnumerable)groups) { DirectoryEntry groupEntry = new DirectoryEntry(group); // 'group' is an IAds ptr object Console.WriteLine(" group = " + groupEntry.Name); } Console.WriteLine(" --- "); } } }