简体   繁体   中英

How do I determine if “DirectoryEntry” found my user?

I am using this simple method of finding a user in the current domain, that works for all users that 'exist' but I can't find any way to determine if the user does not exist.

string userLDAP = @"MYDOMAIN/username";
string path = "WinNT://" + userLDAP ;
DirectoryEntry root = new DirectoryEntry(path, null, null, AuthenticationTypes.Secure);

Other than letting an exception be thrown, how can I use a directory entry to determine if a user does not exist?

 if (root.Properties != null)
      if (root.Properties["objectSid"] != null)  //// EXCEPTION HERE
          if (root.Properties["objectSid"][0] != null)

It's better to use DirectorySearcher for this purpose...

 string userName = "TargetUserName";

        using (DirectorySearcher searcher = new DirectorySearcher("GC://yourdomain.com"))
        {
            searcher.Filter = string.Format("(&(objectClass=user)(sAMAccountName={0}))", userName);

            using (SearchResultCollection results = searcher.FindAll())
            {
                if (results.Count > 0)
                  Debug.WriteLine("Found User");

            }
        }

This sample will search and entire forest including child domains. If you want to target only a single domain use "LDAP://mydomain.com" instead of "GC://mydomain.com". You can also supply searcher.SearchRoot with a DirectoryEntry to use as the root of a search (ie a specific OU or domain).

Don't forget most of the AD stuff is IDisposable so dispose properly as shown above.

I think an easy way to check if your DirectoryEntry object points to an existing AD entry is using the static Exists method.

So your code may look like this:

using(DirectoryEntry de = new DirectoryEntry(....)) {
   // now we check if the related object exists
   bool exists = DirectoryEntry.Exists(de.Path);
   if(exists) {
     // yes  the objects exists
     // do something

   } // end if
} // end using

Of course you can omit the exists variable. I used it just to make the statement more clear.

Are you looking for a specific user, or all users?

I have an application that checks if a user is present by checking the account name - it uses SecurityIdentifier in the System.Security.Principal namespace to check if the Sid is valid.

public bool AccountExists(string name)
        {
            bool SidExists = false;
            try
            {
                NTAccount Acct = new NTAccount(name);
                SecurityIdentifier id = (SecurityIdentifier)Acct.Translate(typeof(SecurityIdentifier));
                SidExists = id.IsAccountSid();
            }
            catch (IdentityNotMappedException)
            {
                //Oh snap.
            }
            return SidExists;
        }

You can specify the Domain when creating your NTAccount object

NTAccount Acct = new NTAccount("SampleDomain", "SampleName");

EDIT

In reference to your comment, would this work for you? Didnt check it, might have to handle a possible null return before evaulating the IsAccountSid() method...

public SecurityIdentifier AccountSID(string myDomain, string myAcct)
{
   SecurityIdentifier id;

   try
   {
     NTAccount Acct = new NTAccount(myDomain, myAcct);
     id = (SecurityIdentifier)Acct.Translate(typeof(SecurityIdentifier));
   }
   catch (IdentityNotMappedException)
   {
     //Oh snap.
   }

   return id;
}

SecurityIdentifier AcctSID = AccountSID("ExampleDomain", "ExampleName");

if (AcctSID.IsAccountSid())
   //Do Something

关于如何检查域中是否存在Windows用户帐户名的此问题的答案可能对您有所帮助。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM