Tuesday, April 25, 2017

ldap query c#

using public ldap test server:

            DirectoryEntry rootEntry = new DirectoryEntry("LDAP://ldap.forumsys.com/cn=read-only-admin,dc=example,dc=com");
            rootEntry.AuthenticationType = AuthenticationTypes.None; //Or whatever it need be
            DirectorySearcher searcher = new DirectorySearcher(rootEntry);
            var queryFormat = "(&(objectClass=user)(objectCategory=person)(|(SAMAccountName=*{0}*)(cn=*{0}*)(gn=*{0}*)(sn=*{0}*)(email=*{0}*)))";
            //TODO searcher.Filter = string.Format(queryFormat, "michael");
            foreach (SearchResult result in searcher.FindAll())
            {
                Console.WriteLine("account name: {0}", result.Properties["samaccountname"].Count > 0 ? result.Properties["samaccountname"][0] : string.Empty);
                Console.WriteLine("common name: {0}", result.Properties["cn"].Count > 0 ? result.Properties["cn"][0] : string.Empty);
            }


read all props:
            var rootEntry = new DirectoryEntry("LDAP://ldap.forumsys.com/cn=read-only-admin,dc=example,dc=com");
            rootEntry.AuthenticationType = AuthenticationTypes.None; //Or whatever it need be
            var searcher = new DirectorySearcher(rootEntry);
            //var queryFormat = "(&(objectClass=user)(objectCategory=person)(|(SAMAccountName=*{0}*)(cn=*{0}*)(gn=*{0}*)(sn=*{0}*)(email=*{0}*)))";
            //TODO searcher.Filter = string.Format(queryFormat, "michael");
            foreach (SearchResult result in searcher.FindAll())
            {
                foreach (var propertyName in result.Properties.PropertyNames)
                {
                    StringBuilder sb = new StringBuilder();
                    string sPropName = propertyName?.ToString();
                    if (!string.IsNullOrEmpty(sPropName))
                    {
                        sb.Append(sPropName + ":");
                        var vals = result.Properties[sPropName];
                        foreach (var val in vals)
                        {
                            sb.Append(val);
                        }

                        Console.WriteLine(sb);
                    }

                }
                Console.WriteLine("-------------------------------------------------------");
            }

No comments: