3

要启用或禁用本地计算机上的用户,我使用以下代码段。

DirectoryEntry localMachine = new DirectoryEntry("WinNT://" + Environment.MachineName);
DirectoryEntry currentUser = localMachine.Children.Find(user, "Administrators");
currentUser.Invoke("AccountDisabled", new object[] { true });
currentUser.CommitChanges();

我将用户分配为字符串。我收到“找不到文件路径错误”:Comexception Unhandled。

我的代码有什么问题吗?

4

4 回答 4

5

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

基本上,您可以定义机器级上下文并在 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 中与用户和组一起玩变得非常容易!

于 2012-07-17T13:03:12.827 回答
2

根据MSDNDirectoryEntry页面:

连接到计算机上的用户。例如,WinNT://<domain name>/<computer name>/<user name>。如果您要连接到本地计算机,WinNT://<computer name>/<user name>

因此,您获取用户的代码应该是:

DirectoryEntry currentUser = new DirectoryEntry("WinNT://" + Environment.MachineName + "/" + user);
于 2012-07-17T12:37:40.227 回答
1

像这样使用

        DirectoryEntry local = new DirectoryEntry("WinNT://localhost");
        DirectoryEntry user = local.Children.Find(username);
        user.InvokeSet("AccountDisabled", true);
        user.CommitChanges();
于 2014-10-02T05:18:05.293 回答
0

尝试使用统一命名约定,即像这样使用“\\”:

DirectoryEntry localMachine = new DirectoryEntry("WinNT:\\" + Environment.MachineName);
于 2012-07-17T12:28:17.657 回答