如何通过ldap中的域名获取用户的用户名和SID

时间:2012-02-28 05:48:30

标签: c# active-directory

我正在尝试获取特定域的用户信息,该域将是该程序的输入。在域名的基础上,它应该返回用户名称/或用户的NT Id和SID的列表。我是ldap编程的新手,任何人都可以帮助我获取此列表。

1 个答案:

答案 0 :(得分:17)

如果您使用的是.NET 3.5及更高版本并且正在讨论Active Directory,那么您应该查看System.DirectoryServices.AccountManagement(S.DS.AM)命名空间。在这里阅读所有相关内容:

基本上,您可以定义域上下文并轻松在AD中查找用户和/或组:

// set up domain context
PrincipalContext ctx = new PrincipalContext(ContextType.Domain);

// find a user
UserPrincipal user = UserPrincipal.FindByIdentity(ctx, "SomeUserName");

if(user != null)
{
   // do something here....     
   var usersSid = user.Sid;

   // not sure what you mean by "username" - the "DisplayName" ? The "SAMAccountName"??
   var username = user.DisplayName;
   var userSamAccountName = user.SamAccountName;
}

新的S.DS.AM让您可以轻松地与AD中的用户和群组一起玩!

更新:如果您需要遍历域的所有用户 - 请尝试以下操作:

您可以使用PrincipalSearcher和“按示例查询”主体进行搜索:

// create your domain context
PrincipalContext ctx = new PrincipalContext(ContextType.Domain);

// define a "query-by-example" principal - here, we search for a UserPrincipal 
UserPrincipal qbeUser = new UserPrincipal(ctx);

// create your principal searcher passing in the QBE principal    
PrincipalSearcher srch = new PrincipalSearcher(qbeUser);

// find all matches
foreach(var found in srch.FindAll())
{
    UserPrincipal user = found as UserPrincipal;

    if(user != null)
    {
       // do whatever here 
       var usersSid = user.Sid;

       // not sure what you mean by "username" - the "DisplayName" ? 
       var username = user.DisplayName;
       var userSamAccountName = user.SamAccountName;
    }
}

更新#2:如果你不能(或者不想)使用S.DS.AM方法 - 这对于Active Directory来说是最简单的 - 到目前为止 - 那么你需要回退到System.DirectoryServices类和方法:

// define the root of your search
DirectoryEntry root = new DirectoryEntry("LDAP://dc=YourCompany,dc=com");

// set up DirectorySearcher  
DirectorySearcher srch = new DirectorySearcher(root);
srch.Filter = "(objectCategory=Person)";
srch.SearchScope = SearchScope.Subtree;

// define properties to load
srch.PropertiesToLoad.Add("objectSid");
srch.PropertiesToLoad.Add("displayName");

// search the directory
foreach(SearchResult result in srch.FindAll())
{
   // grab the data - if present
   if(result.Properties["objectSid"] != null && result.Properties["objectSid"].Count > 1)
   {
       var sid = result.Properties["objectSid"][0];
   }

   if(result.Properties["displayName"] != null && result.Properties["displayName"].Count > 0)
   {
       var userName = result.Properties["displayName"][0].ToString();
   }
}