2011-05-17 79 views
2

我有這樣的代碼從一組獲取用戶

DirectorySearcher myGroupSearcher = new DirectorySearcher(myDirectoryEntry); 
myGroupSearcher.Filter = String.Format("(&(objectClass=group)(|(cn={0})(dn={0})))", strGroupName); 
myGroupSearcher.PropertiesToLoad.Add("member"); 

SearchResult myGroupSearchResult = myGroupSearcher.FindOne(); 

if (myGroupSearchResult != null) 
{ 
    ResultPropertyValueCollection myUsersInGroup = myGroupSearchResult.Properties["member"]; 

    int intMemberCount = myUsersInGroup.Count; 

    for (int i = 0; i < intMemberCount; i++) 
    { 
     //Split the current result 
     string[] strProperites = myUsersInGroup[i].ToString().Split(','); 

     //Get the CN 
     string strUsername = strProperites[0].Substring(3); 

     DirectorySearcher myUserSearcher = new DirectorySearcher(myDirectoryEntry); 
     myUserSearcher.Filter = String.Format("(&(objectClass=user)(|(cn={0})(sAMAccountName={0})))", strUsername); 
     myUserSearcher.PropertiesToLoad.Add("memberOf"); 

     SearchResult myUserSearchResult = myUserSearcher.FindOne(); 

     //Do some work 
    } 
} 

這適用於大多數用戶與用戶的工作,但對於一些人來說,strUserName中得到turncated取決於客戶廣告的樣子(如果用戶有一個CN包含,)。所以這個解決方案不是最優化的。搜索組中的成員時,有沒有辦法獲得samaccount名稱?或者,還有更好的方法?

回答

0
string[] strProperites = myUsersInGroup[i].ToString().Split(new string[] { "cn=" }, StringSplitOptions.RemoveEmptyEntries); 
+0

快速和簡單的解決方案,我的客戶會喜歡它:) – 2011-05-18 09:06:00

7

假設你在.NET 3.5或更高版本(或者可以升級到它),你應該看看System.DirectoryServices.AccountManagement(S.DS.AM)命名空間。在這裏閱讀全部內容:

Managing Directory Security Principals in the .NET Framework 3.5

基本上,你可以定義域範圍內,並可以輕鬆地查找用戶和/或組AD:

// set up domain context 
PrincipalContext ctx = new PrincipalContext(ContextType.Domain); 

// find the group in question 
GroupPrincipal group = GroupPrincipal.FindByIdentity(ctx, "YourGroupNameHere"); 

// if found.... 
if (group != null) 
{ 
    // iterate over members 
    foreach (Principal p in group.GetMembers()) 
    { 
     Console.WriteLine("{0}: {1}", p.StructuralObjectClass, p.DisplayName); 
     // do whatever you need to do to those members 
    } 
} 

新S.DS.AM使它非常容易與AD中的用戶和羣組玩轉:

+1

快17秒,代碼示例...你值+1。 – 2011-05-17 14:19:54

+0

+1對於一個非常好的和明確的答案,雖然很多重建,使其工作。但是我不記得下次有沒有玩AD的時候。 – 2011-05-18 09:07:43

0

這可能是使用System.DirectoryServices.AccountManagement類代替DirectorySearcher的選項。有一個GroupPrincipal類,它具有包含UserPrincipal對象的Members屬性。