using System; using System.DirectoryServices; namespace EnumerateGroupUsers { class Class1 { /// /// The main entry point for the application. /// [STAThread] static void Main(string[] args) { DirectoryEntry domainController = new DirectoryEntry(@"LDAP://"+"MYDOMAIN"+@"/RootDSE"); domainController.AuthenticationType = AuthenticationTypes.Secure; string ldapUrl = @"LDAP://"+domainController.Properties["defaultNamingContext"][0].ToString(); EnlistUsers(ldapUrl, "MYGROUP"); } static void EnlistUsers(string root, string groupName) { string filter; if (null!=groupName) filter = string.Format("(&(objectClass=group)(objectCategory=group)(cn={0}))", groupName); else filter = null; if (null==root) { DirectoryEntry domainController = new DirectoryEntry(@"LDAP://"+"MYDOMAIN"+@"/RootDSE"); domainController.AuthenticationType = AuthenticationTypes.Secure; root = @"LDAP://"+domainController.Properties["defaultNamingContext"][0].ToString(); } DirectorySearcher ds = new DirectorySearcher(new DirectoryEntry(root, null, null, AuthenticationTypes.Secure), filter); ds.SearchScope = SearchScope.Subtree; SearchResultCollection srcGroup = ds.FindAll(); foreach (SearchResult res in srcGroup) { if (res.Properties["objectClass"].Contains("group")) { // this is group, cycle thru' members foreach (object val in res.Properties["member"]) { string s; s = Convert.ToString(val); EnlistUsers("LDAP://" + s, null); } } else // this is a regular user, deal with its data { ResultPropertyValueCollection memberOf = res.Properties["memberof"]; foreach (string s in memberOf) { Console.WriteLine("group: {0}", s); } string name = res.Properties.Contains("givenName") ? (string)res.Properties["cn"][0] : null; string mail = res.Properties.Contains("mail") ? (string)res.Properties["mail"][0] : null; if (null!=name && null!=mail) Console.WriteLine("{0} - {1}", name, mail); foreach (string key in res.Properties.PropertyNames) { foreach (object val in res.Properties[key]) { string s=""; if (null!=val) { if (val.GetType()==typeof(byte[])) { byte[] ab = (byte[])val; if(16==ab.Length) // guid { Guid g = new Guid(ab); s = g.ToString(); } else foreach (byte b in ab) s += b.ToString("X2"); } else s = Convert.ToString(val); } else s = "(null)"; Console.WriteLine("{0}: {1}", key, s); } Console.WriteLine(); } } } } } }