I want to find out by using C#, if a user is a member of an AD group but I am not able to get it to work? I have tried many examples on the net, can anyone help me out? Below is the code:
Code:public void LookupUser() { bool UserExists = false; string UserName = "FrankB@MadeUp.com"; string GroupName = "Europa No.1"; string strPath = "CN="+GroupName+",OU=SomeOU,DC=SomeName,DC=co,DC=uk"; DirectoryEntry userGroup = new DirectoryEntry(strPath); DirectorySearcher searcher = new DirectorySearcher(userGroup); //Set up the LDAP search filter string strFilter = String.Format("(&(objectCategory=person)(objectClass=user)(sAMAccountName={0}))", UserName); searcher.Filter = strFilter; SearchResult result = null; if (searcher != null) { result = searcher.FindOne(); } if(result != null) for (int counter = 0; counter < result.Properties["member"].Count; counter++) { string user = (string)result.Properties["member"][counter]; if(user.ToUpper()==UserName.ToUpper()) { UserExists=true; } else { if(bool.Parse(UserExists.ToString())==true){} else { UserExists=false; } } } }Code:public void LookupUser2 () { string UserName = "FrankB@MadeUp.com"; string GroupName = "Europa No.1"; DirectoryEntry objADAM; DirectoryEntry objGroupEntry; DirectorySearcher objSearchADAM; SearchResultCollection objSearchResults; string strPath; // Construct the binding string. strPath = "CN="+GroupName+",OU=SomeOU,DC=SomeName,DC=co,DC=uk"; // Get the AD LDS object. objADAM = new DirectoryEntry(strPath); objADAM.RefreshCache(); // Get search object, specify filter and scope, // perform search. objSearchADAM = new DirectorySearcher(objADAM); objSearchADAM.Filter = "(&(objectClass=group))"; objSearchADAM.SearchScope = SearchScope.Subtree; objSearchResults = objSearchADAM.FindAll(); // Enumerate groups and members. if (objSearchResults.Count != 0) { foreach(SearchResult objResult in objSearchResults) { objGroupEntry = objResult.GetDirectoryEntry(); Console.WriteLine("Group {0}", objGroupEntry.Name); foreach(object objMember in objGroupEntry.Properties["member"]) { Console.WriteLine(" Member: {0}", objMember.ToString()); } } } else { Console.WriteLine("Results: No groups found."); } }


Reply With Quote
Bookmarks