如何在 C# 中获取 Active Directory 用户帐户属性
How to get Active Directory User Account Attributes in C#
我可以使用以下代码成功获取所有 AD 属性的完整列表(包括 extensionAttribute1
- 15
)
// get whatever attributes are available
List<string> allAttributes = new List<string>();
var context = new DirectoryContext(DirectoryContextType.Forest, "mydomain.com");
using (var schema = System.DirectoryServices.ActiveDirectory.ActiveDirectorySchema.GetSchema(context)) {
var userClass = schema.FindClass("user");
foreach (ActiveDirectorySchemaProperty property in userClass.GetAllProperties()) {
allAttributes.Add(property.Name);
}
}
但是,当我使用以下代码检索用户帐户时,这些属性中的大部分(尤其是 extensionAttribute
s)都不存在:
SearchResultCollection results;
DirectoryEntry de = new DirectoryEntry("LDAP://RootDSE");
DirectorySearcher ds = new DirectorySearcher("LDAP://" + de.Properties["defaultNamingContext"][0].ToString());
ds.Filter = "(&(objectCategory=User)(objectClass=person))";
results = ds.FindAll();
foreach (SearchResult sr in results) {
Console.WriteLine(sr.Properties["extensionAttribute1"][0].ToString()); // == null
}
我做错了什么?
most of these attributes (especially the extensionAttributes) are not present
这是正常的。属性只有在有值时才会返回。如果属性没有值,则根本不返回。
我可以使用以下代码成功获取所有 AD 属性的完整列表(包括 extensionAttribute1
- 15
)
// get whatever attributes are available
List<string> allAttributes = new List<string>();
var context = new DirectoryContext(DirectoryContextType.Forest, "mydomain.com");
using (var schema = System.DirectoryServices.ActiveDirectory.ActiveDirectorySchema.GetSchema(context)) {
var userClass = schema.FindClass("user");
foreach (ActiveDirectorySchemaProperty property in userClass.GetAllProperties()) {
allAttributes.Add(property.Name);
}
}
但是,当我使用以下代码检索用户帐户时,这些属性中的大部分(尤其是 extensionAttribute
s)都不存在:
SearchResultCollection results;
DirectoryEntry de = new DirectoryEntry("LDAP://RootDSE");
DirectorySearcher ds = new DirectorySearcher("LDAP://" + de.Properties["defaultNamingContext"][0].ToString());
ds.Filter = "(&(objectCategory=User)(objectClass=person))";
results = ds.FindAll();
foreach (SearchResult sr in results) {
Console.WriteLine(sr.Properties["extensionAttribute1"][0].ToString()); // == null
}
我做错了什么?
most of these attributes (especially the extensionAttributes) are not present
这是正常的。属性只有在有值时才会返回。如果属性没有值,则根本不返回。