UserPrincipal 有一个方法 GetUnderlyingObject() 将返回 DirectoryEntry。
从 Principal 获取 DirectoryEntry:
private DirectoryEntry GetDirectoryEntryFromUserPrincipal(Principal user)
{
return (DirectoryEntry)user.GetUnderlyingObject();
}
从域和帐户名获取 DirectoryEntry:
private DirectoryEntry GetDirectoryEntryFromDomainAndUsername(string domainName, string userName)
{
// Get the sid from the NT account name
var sid = (SecurityIdentifier) new NTAccount(domainName, accountName)
.Translate(typeof(SecurityIdentifier));
// Get the directory entry for the LDAP service account
var serviceEntry = new DirectoryEntry("LDAP://{address}", "serviceUsername", "servicePassword");
var mySearcher = new DirectorySearcher(serviceEntry)
{
Filter = string.Format("(&(ObjectSid={0}))", sid.Value)
};
return mySearcher.FindOne().GetDirectoryEntry();
}
拥有DirectoryEntry 后,使用Guid 属性获取条目的Object-Guid
private Guid GetObjectGuidFromDirectoryEntry(DirectoryEntry entry)
{
// return the Guid this is the Object-Guid (ignore NativeGuid)
return entry.Guid;
}
针对目录帐户跟踪应用程序中的用户帐户:始终使用 Object-Guid 作为“此值在创建对象时设置且无法更改。”
如果用户更改域或更常见的是更改其名称(婚姻、合法名称更改等),NT 和 SAM 帐户名称可能会更改,并且不应用于跟踪用户。
获取 NT 帐户名(域\用户名):
private string GetNTAccountNameFromDirectoryEntry(DirectoryEntry entry)
{
PropertyValueCollection propertyValueCollection = entry.Properties["objectsid"];
SecurityIdentifier sid = new SecurityIdentifier((byte[]) propertyValueCollection[0], 0);
NTAccount ntAccount = (NTAccount)sid.Translate(typeof (NTAccount));
return account.ToString();
}
获取 SAM-Account-Name (username@domain):
private string GetSAMAccountFromDirectoryEntry(DirectoryEntry entry)
{
return entry.Properties["Name"].Value;
}
这里是所有 Active Directory 属性的exhaustive list。从Properties获取值时使用“Ldap-Display-Name”
例如Properties["Ldap-Display-Name"]
Display-Name (FirstName MI LastName) 可能会派上用场。