2009-12-04 85 views
3

我有一个关于确定帐户名称的类型(用户或组)的问题。
例如,我有两个字符串,分别是“Adventure-works \ david”和“Adventure-works \ admins”, 第一个代表名为david的用户,第二个代表AD组。如何确定帐户的类型(AD用户与AD组)?

我的问题是如何确定这些帐户的类型(用户或AD组)?有没有方便的方法可以使用?

任何意见表示赞赏。 谢谢。

+0

感谢您的回答和您的提醒。 – ddou 2009-12-06 11:16:07

回答

9

你在什么版本的.NET?

如果您使用的是.NET 3.5,请参阅此优秀的MSDN article,了解Active Directory界面的改变方式。

如果你在.NET 3.5中,你可以写:

PrincipalContext ctx = new PrincipalContext(ContextType.Domain, "YOURDOMAIN"); 
Principal myObject = Principal.FindByIdentity(ctx, "your name value"); 

通常情况下,你必须在短短的用户名传递 - 而不是整个域名\用户名 - 反斜杠后的部分串。

这个“校长”现在要么是UserPrincipalGroupPrincipal(也可能一些其它类型的本金,如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(); 
    } 
} 

马克

+0

感谢您的文章,它有很大的帮助。我正在使用.NET 2.0。尽管如此,它需要更多的代码来完成这个任务,它的工作原理。 – ddou 2009-12-04 08:33:14

相关问题