如何确定帐户的类型(AD用户与AD组)?

时间:2009-12-04 06:09:08

标签: c# windows active-directory

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

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

任何评论都表示赞赏。 感谢。

2 个答案:

答案 0 :(得分:10)

你在使用什么版本的.NET?

如果你使用的是.NET 3.5,请参阅这篇关于Active Directory界面如何变化的优秀MSDN article

如果您使用的是.NET 3.5,则可以写:

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

通常,您只需传入用户名 - 反斜杠后面的部分 - 而不是整个DOMAIN \ USERNAME字符串。

这个“校长”现在要么是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();
    }
}

马克

答案 1 :(得分:0)

警告:如果使用DirectorySearcher,则接受的答案可能会失败,因为objectCategory不会返回一致的结果。

考虑改用objectClass

SearchResult sr = ds.FindOne();
bool isUser = sr.Properties["objectClass"]?.Contains("user") == true;
// OR
bool isGroup = sr.Properties["objectClass"]?.Contains("group") == true;
相关问题