我一直在尝试检索在Active Directory用户上设置的两个自定义属性,但似乎我一直在获取一个常量的属性列表(通过2个不同的AD服务器进行测试)
假设我尝试提取的属性是prop1
和prop2
,我在下面的代码中做错了什么:
List<String> nProps = new List<string>();
DirectoryEntry directoryEntry = new DirectoryEntry("WinNT://DOM");
foreach (DirectoryEntry child in directoryEntry.Children)
{
// No filtering; ignore schemes that are not User schemes
if (child.SchemaClassName == "User")
{
foreach (var sVar in child.Properties.PropertyNames)
nProps.Add(sVar.ToString());
break;
}
}
nProps
不包含我的任何自定义属性(不是prop1
也不是prop2
)
(它确实包含其他属性,如BadPasswordAttempts,用户名等)
有什么想法吗?
答案 0 :(得分:3)
您确定自己的属性已设置好吗?如果它们没有设置,它们将不会被列为属性。
如果您正在寻找特定属性,我建议您使用DirectorySearcher
以下示例获取给定用户的company属性。请注意,您首先验证属性是否存在,然后将其解压缩。
DirectoryEntry directoryEntry = new DirectoryEntry("WinNT://DOM");
//Create a searcher on your DirectoryEntry
DirectorySearcher adSearch= new DirectorySearcher(directoryEntry);
adSearch.SearchScope = SearchScope.Subtree; //Look into all subtree during the search
adSearch.Filter = "(&(ObjectClass=user)(sAMAccountName="+ username +"))"; //Filter information, here i'm looking at a user with given username
SearchResult sResul = adSearch.FindOne(); //username is unique, so I want to find only one
if (sResult.Properties.Contains("company")) //Let's say I want the company name (any property here)
{
string companyName = sResult.Properties["company"][0].ToString(); //Get the property info
}
答案 1 :(得分:-2)
虽然不是您问题的直接答案,但以下是我们使用的内容:
public static string GetProperty(string adUserId, string domain, string lDAPLoginId, string lDAPPassword, string propertyName)
{
PrincipalContext ctx = new PrincipalContext(ContextType.Domain, domain, lDAPLoginId, lDAPPassword);
UserPrincipal up = UserPrincipal.FindByIdentity(ctx, IdentityType.SamAccountName, adUserId);
string result = "";
if (up != null)
{
result = PrincipalGetProperty(up, propertyName);
}
return result;
}