c#-如何确定“ DirectoryEntry”是否找到我的用户?

我正在使用这种在当前域中查找用户的简单方法,该方法适用于“存在”的所有用户,但是我找不到任何方法来确定该用户是否不存在.

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)

解决方法:

为此,最好使用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的,因此请按照上面所示正确处理.

上一篇:java – 连接到Ldap


下一篇:c#-无法使用LDAP验证凭据