2012-04-02 44 views
1

我們使用以下代碼來獲取活動目錄用戶的組。域用戶組未獲取活動目錄用戶

StringCollection groups = new StringCollection(); 

try 
{ 
    using (PrincipalContext pc = new PrincipalContext(ContextType.Domain, domainName, userName, password)) 
    { 
     //find user roles 
     UserPrincipal user = UserPrincipal.FindByIdentity(pc, IdentityType.SamAccountName, loginUserName); 

     if (user != null) 
     { 
     DirectoryEntry de = (DirectoryEntry)user.GetUnderlyingObject(); 
     object obGroups = de.Invoke("Groups");       

     foreach (object ob in (IEnumerable)obGroups) 
     { 
      DirectoryEntry obGpEntry = new DirectoryEntry(ob);        
      groups.Add(obGpEntry.Name); 
     }  
     } 
    } 
} 
catch (Exception e) 
{ 
} 

這幾乎和預期一樣。但是,當我們用Domain Users組檢查用戶時,該方法沒有返回組名。有些用戶只使用這個Domain Users組,當我們爲這些用戶調用這個方法時,它返回一個空組。

任何建議,請..

回答

2

這是一個衆所周知的和記載「不作爲」,即所謂的主組是Groups方法在此代碼返回。有一些比較神祕的方法 - 或者嘗試這種方法:

如果您使用的是.NET 3.5或更高版本,則應該檢查System.DirectoryServices.AccountManagement(S.DS.AM)命名空間。在這裏閱讀全部內容:

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

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

// find a user 
UserPrincipal user = UserPrincipal.FindByIdentity(ctx, "SomeUserName"); 

if(user != null) 
{ 
    // the call to .GetAuthorizationGroups() will return **all** groups that 
    // user is a member of - including the primary group and all nested 
    // group memberships, too! 
    var result = user.GetAuthorizationGroups(); 
} 

的新的S.DS.AM可以很容易地與AD中的用戶和羣組玩耍!

更新:如果你堅持使用舊的傳統技術,檢查出this blog post by Ryan Dunn這解釋很詳細的如何獲得初級組在C#中的AD帳戶。

+0

是的,我以前用過這個,但是後來出現一個錯誤,例如「無法檢索域的信息(1355)」。我無法弄清楚原因,於是我轉而使用舊技術。 – 2012-04-02 05:08:13

+0

給定的鏈接現在顯示404錯誤http://dunnry.com/blog/2005/01/18/DeterminingYourPrimaryGroupInActiveDirectoryUsingNET.aspx%24 – 2012-04-02 05:30:56

+0

@mahesh:抱歉,粘貼後有一個額外的字符 - 修復,現在的作品。 – 2012-04-02 05:32:59

相關問題