Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/273.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 通过employeeID获取UserPrincipal_C#_Asp.net 4.0_Account Management - Fatal编程技术网

C# 通过employeeID获取UserPrincipal

C# 通过employeeID获取UserPrincipal,c#,asp.net-4.0,account-management,C#,Asp.net 4.0,Account Management,我已经实现了System.DirectoryServices.AccountManagement,以便在我的webapps中通过给定用户名的身份查找用户(UserPrincipal)。然而,我有几个例子,我需要得到广告帐户,只有一个雇员ID。在AccountManagement中,有没有一种好方法可以为UserPrincipal(甚至只是sAMAccountName)提供一个employeeID 我目前正在通过用户名抓取用户: PrincipalContext adAuth = new Prin

我已经实现了System.DirectoryServices.AccountManagement,以便在我的webapps中通过给定用户名的身份查找用户(UserPrincipal)。然而,我有几个例子,我需要得到广告帐户,只有一个雇员ID。在AccountManagement中,有没有一种好方法可以为UserPrincipal(甚至只是sAMAccountName)提供一个employeeID

我目前正在通过用户名抓取用户:

PrincipalContext adAuth = new PrincipalContext(ContextType.Domain, Environment.UserDomainName);

//get user
UserPrincipal usr = UserPrincipal.FindByIdentity(adAuth, username);

我一直在搜索,似乎找不到答案来确认这是否可以完成。如果我不能使用AccountManagement,那么获得sAMAccountName的employeeID的最佳方法是什么?

因此,我找到了一种使用System.DirectoryServices的方法,如下所示,但它似乎相当长:

string username = "";

DirectoryEntry entry = new DirectoryEntry(_path);

//search for a DirectoryEntry based on employeeID
DirectorySearcher search = new DirectorySearcher(entry);
search.Filter = "(employeeID=" + empID + ")";

//username
search.PropertiesToLoad.Add("sAMAccountName");

SearchResult result = search.FindOne();

//get sAMAccountName property
username = result.Properties["sAMAccountName"][0].ToString();

当然,我可以将其用于其他属性,但我非常喜欢AccountManagement的强类型属性。

您不需要超出System.DirectoryServices.AccountManagement命名空间

UserPrincipal searchTemplate = new UserPrincipal(adAuth);
searchTemplate.EmployeeID = "employeeID";
PrincipalSearcher ps = new PrincipalSearcher(searchTemplate);

UserPrincipal user = (UserPrincipal)ps.FindOne();
在本例中,如果未找到用户,则用户对象将为null。如果要查找UserPrinicipal对象的集合,可以在PrincipalSearcher(ps)对象上使用FindAll方法


还要注意,FindOne方法返回一个Principal对象,但我们知道它实际上是一个UserPrincipal,应该这样处理(casted),因为UserPrincipal是搜索过滤器的一部分

我知道这是一篇老文章,但如果它运行良好,我会尝试给出一个正确的答案。谢谢