2014-02-23 128 views
0

我試圖從使用C#的Active Directory組中刪除某個用戶。 這是我應該處理我的任務的一段代碼,儘管它目前不工作。從Active Directory組中刪除用戶

public static bool RemoveUserFromGroup(string UserId, string GroupId) 
{ 
    using (var directory = new DirectoryEntry("LDAP://server")) 
    { 
     using (var dSearch = new DirectorySearcher(directory)) 
     { 
      try 
      { 
       dSearch.Filter = "(sAMAccountName=" + UserId + ")"; 
       SearchResult sr = dSearch.FindOne(); 
       System.DirectoryServices.PropertyCollection UserProperties = sr.GetDirectoryEntry().Properties; 
       if(UserProperties == null) 
        return false; 
       foreach(object Group in UserProperties["memberOf"]) 
       { 
        if(Group.ToString() == GroupId) 
        { 
         UserProperties["memberOf"].Remove(GroupId); 
         directory.CommitChanges(); 
         directory.Close(); 
         return true; 
        } 
       } 
      } 
      catch (Exception e) 
      { 
       return false; 
      } 
     } 
    } 
    return false; 
} 

請原諒我,如果有此代碼中的任何錯別字,我不得不手動從我開發的機器,它沒有網絡連接的傷心地複製它。

+0

的[添加和Active Directory組在.NET中移除用戶]可能重複(http://stackoverflow.com/questions/2143052/adding-and-removing- users-from-active-directory-groups-in-net) – har07

回答

1

Use

public void RemoveUserFromGroup(string userId, string groupName) 
{ 
    try 
    { 
     using (PrincipalContext pc = new PrincipalContext(ContextType.Domain, "COMPANY")) 
     { 
      GroupPrincipal group = GroupPrincipal.FindByIdentity(pc, groupName); 
      group.Members.Remove(pc, IdentityType.UserPrincipalName, userId); 
      group.Save(); 
     } 
    } 
    catch (System.DirectoryServices.DirectoryServicesCOMException E) 
    { 
     //doSomething with E.Message.ToString(); 

    } 
} 
+0

我已經嘗試過使用這種方法,但它對我無效。我收到消息「找不到與指定參數匹配的主體」。當我進入調試模式時,我可以看到「成員」的計數會拋出異常,但如果單擊「結果視圖」並展開結果,我會看到實際的組成員。雖然,似乎我無法訪問它們。有任何想法嗎? –

+6

通過將「IdentityType.UserPrincipalName」切換爲「IdentityType.SamAccountName」來繞過此錯誤。 –

0
public string RemoveUserFromList(string UserID, string ListName) 
    { 
     try 
     { 
      using (PrincipalContext pc = new PrincipalContext(ContextType.Domain, "DomainName", UserName, Password)) 
      { 
       GroupPrincipal group = GroupPrincipal.FindByIdentity(pc, ListName); 
       group.Members.Remove(pc, IdentityType.SamAccountName, UserID); 
       group.Save(); 
      } 
      return "Success"; 
     } 
     catch (Exception ex) 
     { 
      return ex.Message; 
     } 
    } 
相關問題