使用c#删除活动目录中的用户

我写了一些代码,但没有工作,它抛出exception“发生了一个操作错误。” 代码—>

DirectoryEntry dirEntry = new DirectoryEntry("LDAP path", "admin-username", "admin-password"); dirEntry.Properties["member"].Remove("username-delete"); dirEntry.CommitChanges(); dirEntry.Close(); 

给我一些想法摆脱这些事情..

如果您使用的是.NET 3.5及更高版本,则应查看System.DirectoryServices.AccountManagement (S.DS.AM)命名空间。 在这里阅读所有相关内容:

  • 管理.NET Framework 3.5中的目录安全性主体
  • System.DirectoryServices.AccountManagement上的MSDN文档

基本上,您可以定义域上下文并在AD中轻松查找用户和/或组:

 // set up domain context PrincipalContext ctx = new PrincipalContext(ContextType.Domain); // find the user you want to delete UserPrincipal user = UserPrincipal.FindByIdentity(ctx, "SomeUserName"); if(user != null) { user.Delete(); } 

新的S.DS.AM使得在AD中与用户和群组玩起来非常容易!

当您已经使用DirectoryEntry时,不需要PrincipalContext或UserPrincipal。

您只需使用DeleteTree()方法:

 DirectoryEntry dirEntry = new DirectoryEntry("LDAP path", "admin-username", "admin-password"); dirEntry.DeleteTree();