无法使用System.DirectoryServices.AccountManagement.UserPrincipal

本文关键字:DirectoryServices AccountManagement UserPrincipal System | 更新日期: 2023-09-27 18:19:52

我正在尝试使用System.DirectoryServices.AccountManagement.UserPrincipal 删除本地用户帐户

我使用的是在Windows Server 2008 R2 Enterprise SP1 上运行的VS 2010

这是我的代码

using (var ctx = new PrincipalContext(ContextType.Machine))
{
    using (var up = UserPrincipal.FindByIdentity(ctx, "test1"))
    {                        
        if (up != null)
        {
            up.Delete();
        }
    }                       
}

当调用up.Delete()时,我收到异常,并显示以下消息:

位于路径中的Active Directory对象WinNT://DOMAIN/MACHINENAME不是容器。

我应该怎么做才能使Delete()工作?

无法使用System.DirectoryServices.AccountManagement.UserPrincipal

您可以尝试在FindByIdentity重载中指定identityType参数:

using (var up = UserPrincipal.FindByIdentity(ctx, IdentityType.SamAccountName, "test1"))

下面是一段对我有用的代码:

try
{
  PrincipalContext domainContext = new PrincipalContext(ContextType.Domain, "WM2008R2ENT:389", "dc=dom,dc=fr", "jpb", "pwd");
  /* Retreive a user
   */
  UserPrincipal user = UserPrincipal.FindByIdentity(domainContext, "user3");
  if (user != null)
    user.Delete();
}
catch (Exception e)
{
  Console.WriteLine(e.Message);
}
Console.WriteLine("Done!");

已编辑

因此,对于本地机器(SAM),它如下所示,与您的代码完全相同,但如果代码没有在提升权限的管理员提示下运行,则异常管理会显示拒绝访问错误。我认为你的错误就源于此。

try
{
  PrincipalContext computerContext = new PrincipalContext(ContextType.Machine);
  /* Retreive a user
   */
  UserPrincipal user = UserPrincipal.FindByIdentity(computerContext, "utilisateur1");
  if (user != null)
    user.Delete();
}
catch (Exception e)
{
  Console.WriteLine(e.Message);
}
Console.WriteLine("Done!");

Console.ReadLine();

相关文章:
  • 没有找到相关文章