要在本地计算机上启用或禁用用户,我使用以下代码段。
DirectoryEntry localMachine = new DirectoryEntry("WinNT://" + Environment.MachineName);
DirectoryEntry currentUser = localMachine.Children.Find(user, "Administrators");
currentUser.Invoke("AccountDisabled", new object[] { true });
currentUser.CommitChanges();
我将用户指定为字符串。我收到“找不到文件路径错误”:Comexception Unhandled。
我的代码有什么问题吗?
最佳答案
如果您使用的是 .NET 3.5 及更高版本,则应查看 System.DirectoryServices.AccountManagement
(S.DS.AM) 命名空间。在这里阅读所有相关信息:
- Managing Directory Security Principals in the .NET Framework 3.5
- MSDN docs on System.DirectoryServices.AccountManagement
基本上,您可以定义机器级上下文并在 AD 中轻松找到用户和/或组:
// set up domain context
PrincipalContext ctx = new PrincipalContext(ContextType.Machine);
// find a user
UserPrincipal user = UserPrincipal.FindByIdentity(ctx, "SomeUserName");
if(user != null)
{
user.Enabled = false;
user.Save();
}
新的 S.DS.AM 使得在 AD 中与用户和组一起玩真的很容易!
关于c# - 在本地计算机上启用或禁用用户,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11522336/