2014-09-29 70 views
0

我正在開發一個項目,希望允許通過Active Directory和我們使用的一些其他應用程序創建單擊用戶。UserPrincipal返回已登錄用戶

我與

using System.DirectoryServices.AccountManagement; 

命名空間的工作和

UserPrinciple 

對象

是我遇到的問題是,它只會返回登錄的用戶,甚至當我通過另一位用戶進入方法

這是一些代碼

對於將用戶添加到一個新的組

public bool AddUserToGroup(string sUserName, string sGroupName) 
     { 
      try 
      { 
       UserPrincipal oUserPrincipal = GetUser(sUserName); 
       Trace.WriteLine(oUserPrincipal.Context); 
       GroupPrincipal oGroupPrincipal = GetGroup(sGroupName); 
       if (oGroupPrincipal != null) 
       { 
        if (!IsUserGroupMember(sUserName, sGroupName)) 
        { 
         oGroupPrincipal.Members.Add(pp); 
         oGroupPrincipal.Save(); 
        } 
       } 
       return true; 
      } 
      catch 
      { 
       return false; 
      } 
     } 

這裏是的getUser()

UserPrincipal oUserPrincipal = UserPrincipal.FindByIdentity(oPrincipalContext, sUserName); 
      return oUserPrincipal; 

但它只返回登錄的用戶。

讓我知道如果你需要任何更多信息...

我期待一些答覆:)

馬丁

編輯PrincipalContext方法

PrincipalContext oPrincipalContext = new PrincipalContext(ContextType.Domain, sDomain, sDefaultOU, ContextOptions.SimpleBind, sServiceUser, sServicePassword); 
      return oPrincipalContext; 
+0

你能分享您的實例代碼tiate'oPrincipalContext'? – 2014-09-29 14:16:23

+0

更新了我的主要問題 – 2014-09-29 14:38:22

回答

0

我發現您必須將帳戶類型傳遞給GetUser方法

所以原本是

UserPrincipal oUserPrincipal = UserPrincipal.FindByIdentity(oPrincipalContext, sUserName); 
      return oUserPrincipal; 

現在是這樣

UserPrincipal oUserPrincipal = UserPrincipal.FindByIdentity(oPrincipalContext, IdentityType.SamAccountName, sUserName); 
     return oUserPrincipal; 

如果你不指定

IdentityType.SamAccountName 

它看起來本地

馬丁