我有一个关于确定帐户名称的types(用户或组)的问题。
例如,我有两个string,分别是“Adventure-works \ david”和“Adventure-works \ admins”,第一个表示名为david的用户,第二个表示AD组。
我的问题是如何确定这些帐户的types(用户或AD组)? 有没有方便的方法可以使用?
任何意见表示赞赏。 谢谢。
你在什么版本的.NET?
如果您使用的是.NET 3.5,请参阅这篇极好的MSDN文章 ,了解Active Directory接口如何改变。
如果你在.NET 3.5上,你可以写:
PrincipalContext ctx = new PrincipalContext(ContextType.Domain, "YOURDOMAIN"); Principal myObject = Principal.FindByIdentity(ctx, "your name value");
通常,您只需传入用户名即反斜杠之后的部分,而不是整个DOMAIN \ USERNAME字符串。
这个“Principal”现在是一个UserPrincipal
或一个GroupPrincipal
(或者它可以是其他类型的主体,例如ComputerPrincipal
):
if(myObject is UserPrincipal) { // you have a user } else if(myObject is GroupPrincipal) { // you have a group }
你可以从那里继续
如果您使用的是.NET 1.x / 2.0 / 3.0版本,则需要使用稍微复杂一点的创建DirectorySearcher
和搜索对象的过程:
// create root DirectoryEntry for your search DirectoryEntry deRoot = new DirectoryEntry("LDAP://dc=YourCompany,dc=com"); // create searcher DirectorySearcher ds = new DirectorySearcher(deRoot); ds.SearchScope = SearchScope.Subtree; // define LDAP filter - all you can specify is the "anr" (ambiguous name // resolution) attribute of the object you're looking for ds.Filter = string.Format("(anr={0})", "YourNameValue"); // define properties you want in search result(s) ds.PropertiesToLoad.Add("objectCategory"); ds.PropertiesToLoad.Add("displayName"); // search SearchResult sr = ds.FindOne(); // check if we get anything back, and if we can check the "objectCategory" // property in the search result if (sr != null) { if(sr.Properties["objectCategory"] != null) { // objectType will be "Person" or "Group" (or something else entirely) string objectType = sr.Properties["objectCategory"][0].ToString(); } }
渣子