如何确定"DirectoryEntry"是否找到了我的用户?

3

我正在使用这种简单的方法在当前域中查找用户,对于所有“存在”的用户都有效,但我无法找到任何确定用户不存在的方法。

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

除了让异常抛出之外,我如何使用目录条目来确定用户不存在呢?

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

6

为了实现这个目的,最好使用DirectorySearcher...

 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");

            }
        }

这个示例将搜索整个包括子域在内的林。如果您只想针对单个域,请使用“LDAP://mydomain.com”而不是“GC://mydomain.com”。您还可以提供searcher.SearchRoot以DirectoryEntry形式使用作为搜索的根(即特定OU或域)。

不要忘记大多数AD内容都是IDisposable,所以请像上面显示的那样正确处理。


1
我认为一个简单的检查您的对象是否指向现有AD条目的方法是使用静态的方法。
因此,您的代码可能如下所示:
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

当然,您可以省略exists变量。我只是用它来使语句更清晰。

0
你是在寻找特定用户,还是所有用户?
我有一个应用程序,它通过检查账户名称来检查用户是否存在 - 它使用System.Security.Principal命名空间中的SecurityIdentifier来检查Sid是否有效。
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;
        }

在创建NTAccount对象时,您可以指定域。

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

编辑

关于您的评论,这个方案对您是否可行?没有检查过,需要在评估IsAccountSid()方法之前处理可能的空返回值...

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

我正在寻找一个特定的用户。我的目标是获取一个SID,以便将其添加到SSAS角色中。 - makerofthings7

0

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接