2015-06-14 93 views
0

我試圖用c#代碼獲取活動目錄中的所有用戶組。從C#中的活動目錄中獲取所有用戶的組

這是我的代碼:

private List<GroupPrincipal> GetGroups() 
{ 
    string userName = User.Identity.Name; 
    string host = Request.Url.Host.ToLower(); 
    List<GroupPrincipal> result = new List<GroupPrincipal>(); 

    UserPrincipal user = UserPrincipal.FindByIdentity(new PrincipalContext(ContextType.Domain, host), IdentityType.SamAccountName, userName); 
    foreach (GroupPrincipal group in user.GetGroups()) 
    { 
     result.Add(group); 
    } 
    return result; 
} 

我是由該說,該服務器無法連接UserPrincipal用戶啓動該行收到一個錯誤。我從服務器上運行我的代碼,以便連接它。

我到底做錯了什麼?

預先感謝您!

+0

你從Web應用程序這樣做呢? – Garett

+0

是的,我是。我正在使用asp應用程序 –

回答

0

要連接Active Directory,請創建PrincipalContext對象。

PrincipalContext insPrincipalContext = new PrincipalContext(ContextType.Domain, "MyDomain", 
            "DC=MyDomain,DC=com"); 

代碼來獲取所有羣組: 創建GroupPrincipal對象並調用SearchGroups()返回給定域的所有組的列表。

 private void ListGroups(){ 
     GroupPrincipal insGroupPrincipal = new GroupPrincipal(insPrincipalContext); 
     insGroupPrincipal.Name = "*"; 
     SearchGroups(insGroupPrincipal);} 

    private void SearchGroups(GroupPrincipal parGroupPrincipal) 
    { 
     List<Principal> oList = new List<Principal>(); 
     PrincipalSearcher insPrincipalSearcher = new PrincipalSearcher(); 
     insPrincipalSearcher.QueryFilter = parGroupPrincipal; 
     PrincipalSearchResult<Principal> results = insPrincipalSearcher.FindAll(); 
     foreach (Principal p in results) 
     { 
      oList.Add(p); 
     } 
    } 

這個鏈接也可以幫助你 - http://www.codeproject.com/Articles/38344/Using-System-DirectoryServices-AccountManagement

相關問題