use*_*285 5 c# active-directory
如何从与用户关联的 Active Directory 管理员获取管理员姓名和电子邮件地址等详细信息?
我能够获得用户的所有详细信息:
ActiveDirectory.SearchUserinAD("ads", "sgupt257");
public static bool SearchUserinAD(string domain, string username)
{
using (var domainContext = new PrincipalContext(ContextType.Domain, domain))
{
using (var user = new UserPrincipal(domainContext))
{
user.SamAccountName = username;
using (var pS = new PrincipalSearcher())
{
pS.QueryFilter = user;
var results = pS.FindAll().Cast<UserPrincipal>();
{
foreach (var item in results)
{
File.WriteAllText("F:\\webapps\\CIS\\UserInfo.txt", item.DisplayName + item.Name + item.EmailAddress + item.EmployeeId + item.VoiceTelephoneNumber + item.Guid + item.Context.UserName + item.Sid);
}
if (results != null && results.Count() > 0)
{
return true;
}
}
}
}
}
return false;
}
Run Code Online (Sandbox Code Playgroud)
谢谢。
我使用 DirectorySearcher 从 AD 获取数据。你可以得到这样的经理:
DirectoryEntry dirEntry = new DirectoryEntry("LDAP://DC=company,DC=com");
DirectorySearcher search = new DirectorySearcher(dirEntry);
search.PropertiesToLoad.Add("cn");
search.PropertiesToLoad.Add("displayName");
search.PropertiesToLoad.Add("manager");
search.PropertiesToLoad.Add("mail");
search.PropertiesToLoad.Add("sAMAccountName");
if (username.IndexOf('@') > -1)
{
// userprincipal username
search.Filter = "(userPrincipalName=" + username + ")";
}
else
{
// samaccountname username
String samaccount = username;
if (username.IndexOf(@"\") > -1)
{
samaccount = username.Substring(username.IndexOf(@"\") + 1);
}
search.Filter = "(sAMAccountName=" + samaccount + ")";
}
SearchResult result = search.FindOne();
result.Properties["manager"][0];
Run Code Online (Sandbox Code Playgroud)
现在您知道谁是经理,因此您可以查询有关经理的数据。
如果您想使用 Principals 而不是 DirectorySearcher,您可以调用GetUnderlyingObject()UserPrincipal 对象并为其获取 DirectoryEntry。
using(var user = new UserPrincipal(domainContext))
{
DirectoryEntry dEntry = (DirectoryEntry)user.GetUnderlyingObject();
Object manager = dEntry.Properties["manager"][0];
}
Run Code Online (Sandbox Code Playgroud)