問題描述
我有一個關于確定帳戶名稱類型(用戶或組)的問題.
例如,我有兩個字符串,比如Adventure-worksdavid"和Adventure-worksadmins",第一個代表名為 david 的用戶,第二個代表一個 AD 組.
I have a question about determining the type (User or Group) of a account name.
For example, I have two strings, say "Adventure-worksdavid" and "Adventure-worksadmins",
the first represents a user named david, and the second represents an AD group.
我的問題是如何確定這些帳戶的類型(用戶或 AD 組)?有什么方便的方法可以用嗎?
My question is how can I determin the type(User or AD group) of these account? Are there convenient method I can use?
感謝任何評論.謝謝.
推薦答案
您使用的是哪個版本的 .NET?
What version of .NET are you on??
如果您使用 .NET 3.5,請參閱這篇優秀的MSDN 文章,了解如何Active Directory 界面發生了很大變化.
If you're on .NET 3.5, see this excellent MSDN article on how the Active Directory interface has changed quite a bit.
如果你使用 .NET 3.5,你可以寫:
If you're on .NET 3.5, you could write:
PrincipalContext ctx = new PrincipalContext(ContextType.Domain, "YOURDOMAIN");
Principal myObject = Principal.FindByIdentity(ctx, "your name value");
通常,您必須只傳入用戶名 - 反斜杠后的部分 - 而不是整個 DOMAINUSERNAME 字符串.
Typically, you'd have to pass in just the user name - the part after the backslash - not the whole DOMAINUSERNAME string.
這個主體"現在要么是 UserPrincipal
要么是 GroupPrincipal
(或者它可以是其他類型的主體,例如 ComputerPrincipal
):
This "Principal" now either is a UserPrincipal
or a GroupPrincipal
(or it could some other type of principal, e.g. 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
并搜索您的對象:
If you're on .NET 1.x/2.0/3.0, you'd have to use the slightly more involved procedure of creating a DirectorySearcher
and searching for your object:
// 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();
}
}
馬克
這篇關于如何確定帳戶的類型(AD 用戶與 AD 組)?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!