[英]Find username from Active Directory using email id
我通過傳遞電子郵件 ID 從 Active Directory 中查找用戶名。 它工作正常。 但是獲取用戶名需要 30-40 秒。 還有其他更好的方法可以通過電子郵件地址從 Active Directory 中查找用戶名嗎?
請參考我的代碼:
using (PrincipalContext context = new PrincipalContext(ContextType.Domain, "domainname"))
{
UserPrincipal userPrincipal = new UserPrincipal(context);
PrincipalSearcher principalSearch = new PrincipalSearcher(userPrincipal);
foreach (UserPrincipal result in principalSearch.FindAll())
{
if (result != null && result.EmailAddress != null && result.EmailAddress.Equals(user.Email, StringComparison.OrdinalIgnoreCase))
{
user.FirstName = result.GivenName;
user.LastName = result.Surname;
}
}
}
您無需枚舉所有用戶即可找到其中之一! 試試這個代碼:
using (PrincipalContext context = new PrincipalContext(ContextType.Domain, "domainname"))
{
UserPrincipal yourUser = UserPrincipal.FindByIdentity(context, EmailAddress);
if (yourUser != null)
{
user.FirstName = yourUser.GivenName;
user.LastName = yourUser.Surname;
}
}
如果這不起作用,或者如果您需要一次搜索多個條件,請將PrincipalSearcher
與 QBE(按示例查詢)方法一起使用 -搜索您需要的一個用戶 - 不要在所有用戶之間循環!
// create your domain context
using (PrincipalContext context = new PrincipalContext(ContextType.Domain, "domainname"))
{
// define a "query-by-example" principal -
UserPrincipal qbeUser = new UserPrincipal(ctx);
qbeUser.EmailAddress = yourEmailAddress;
// create your principal searcher passing in the QBE principal
PrincipalSearcher srch = new PrincipalSearcher(qbeUser);
// find all matches
foreach(var found in srch.FindAll())
{
// do whatever here - "found" is of type "Principal" - it could be user, group, computer.....
}
}
using System.DirectoryServices.AccountManagement;
// Lock user
using (PrincipalContext context = new PrincipalContext(ContextType.Domain))
{
UserPrincipal yourUser = UserPrincipal.FindByIdentity(context, logonName);
if (yourUser != null)
{
if(!yourUser.IsAccountLockedOut())
{
yourUser.Enabled = False;
yourUser.Save();
}
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.