我有一個關於確定帳戶名稱的類型(用戶或組)的問題。
例如,我有兩個字符串,分別是「Adventure-works \ david」和「Adventure-works \ admins」, 第一個代表名爲david的用戶,第二個代表AD組。如何確定帳戶的類型(AD用戶與AD組)?
我的問題是如何確定這些帳戶的類型(用戶或AD組)?有沒有方便的方法可以使用?
任何意見表示讚賞。 謝謝。
我有一個關於確定帳戶名稱的類型(用戶或組)的問題。
例如,我有兩個字符串,分別是「Adventure-works \ david」和「Adventure-works \ admins」, 第一個代表名爲david的用戶,第二個代表AD組。如何確定帳戶的類型(AD用戶與AD組)?
我的問題是如何確定這些帳戶的類型(用戶或AD組)?有沒有方便的方法可以使用?
任何意見表示讚賞。 謝謝。
你在什麼版本的.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");
通常情況下,你必須在短短的用戶名傳遞 - 而不是整個域名\用戶名 - 反斜槓後的部分串。
這個「校長」現在要麼是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();
}
}
馬克
感謝您的文章,它有很大的幫助。我正在使用.NET 2.0。儘管如此,它需要更多的代碼來完成這個任務,它的工作原理。 – ddou 2009-12-04 08:33:14
感謝您的回答和您的提醒。 – ddou 2009-12-06 11:16:07