How to set the directory search filter for UPN in Active Directory

Renu Kashiramka 0 Reputation points
2023-03-27T03:07:47.4533333+00:00

string searchFilter = "(" + obj.MatchingCriteriaAttributeName + " = " + MatchingCriteriaAttributeValue + ")";

which set as (userPrincipalName=a@domainname)

passed in


        public bool UserExists(string username, string password, string searchRootpath, string searchFilter,string objectGuid,out string dnName)
        {
            dnName = null;
            string sAccount = username.Replace(@"NOA\", "");
            // Get root of directory entry given credentials and search root           
            using (DirectoryEntry rootDomaintoStart = searchRootpath == null ? new DirectoryEntry(GetCurrentDomainPath()) : new DirectoryEntry(searchRootpath, username, password))
            {
                // Create new instance of directory searcher with directory entry root
                DirectorySearcher search = new DirectorySearcher(rootDomaintoStart);
                // search.Filter = "(SAMAccountName=" + sAccount + ")";
                //if (!string.IsNullOrEmpty(objectGuid))
               search.Filter = searchFilter;
                //else
                SearchResult result;
                //  global.MessageBox.Show(deSearch.Filter.ToString());
                try
                {
                   result = search.FindOne();
                }
                catch (Exception)
                {

                    throw;
                }
                

                if (null == result)
                {
                    dnName = null;
                    return false;
                }
Active Directory
Active Directory
A set of directory-based technologies included in Windows Server.
6,419 questions
0 comments No comments
{count} votes

1 answer

Sort by: Most helpful
  1. Limitless Technology 44,221 Reputation points
    2023-03-27T12:19:17.0533333+00:00
    Hello there,
    
    Found this script online which is used to set the directory search filter for UPN in Active Directory.
    
    public String findUserByUPN( LdapContext ctx, String username )
    {
       // Domain name should be in DC=your,DC=domain,DC=com format
       String domain = "DC=demo,DC=com";
       String filter = "(userPrincipalName=" + username + ")" ;
       NamingEnumeration<SearchResult> results = ctx.search( domain, filter, null );
       while ( results.hasMore() )
       {
           SearchResult result = results.next();
           // If you get a result here, the user was found
           return result.getNameInNamespace();
       }
       return null;
    }
    
    Hope this resolves your Query !!
    
    --If the reply is helpful, please Upvote and Accept it as an answer–
    
    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.