.net 作为另一用户的子对象创建的本地用户

.net 作为另一用户的子对象创建的本地用户,.net,active-directory,.net,Active Directory,我们有一个域,sfb ber,这个域中的一个用户,sfb ber\sfb,具有samAccountNamesfb,这个域中有一台机器,sfb.sfb ber.local,具有samAccountNamesfb$。我正在尝试使用以下代码在此计算机上创建本地用户: var context = new PrincipalContext(ContextType.Machine); var userPrincipal = new UserPrincipal(context, "testusr", "tes

我们有一个域,
sfb ber
,这个域中的一个用户,
sfb ber\sfb
,具有
samAccountName
sfb,这个域中有一台机器,
sfb.sfb ber.local
,具有
samAccountName
sfb$
。我正在尝试使用以下代码在此计算机上创建本地用户:

var context = new PrincipalContext(ContextType.Machine);
var userPrincipal = new UserPrincipal(context, "testusr", "testpwd", true);
userPrincipal.Save();

var entry = (DirectoryEntry)userPrincipal.GetUnderlyingObject();
Console.WriteLine("{0} {1}", entry.SchemaEntry.Name, entry.Path);
Console.WriteLine("{0} {1}", entry.Parent.SchemaEntry.Name, entry.Parent.Path);
Console.WriteLine("{0} {1}", entry.Parent.Parent.SchemaEntry.Name, entry.Parent.Parent.Path);
用户创建成功后,代码将打印出以下内容:

User WinNT://SFB-BER/SFB/testusr
User WinNT://SFB-BER/SFB
Domain WinNT://SFB-BER

用户似乎被创建为现有
sfb
用户的子对象,而不是
sfb.sfb ber.local
计算机。这会在以后尝试以编程方式删除用户时产生问题。在不重命名机器的情况下,如何防止出现这种情况


编辑:最后,我们选择不以编程方式创建用户,而是记录此边缘案例,并要求系统管理员手动创建。我仍然想知道如何解决这个问题,所以我会在获得更多代表后立即分配新的赏金。

尝试使用域级上下文,而不是机器:

using(var pc = new PrincipalContext(ContextType.Domain))
{
  using(var up = new UserPrincipal(pc))
  {
    up.SamAccountName = username;
    up.EmailAddress = email;
    up.SetPassword(password);
    up.Enabled = true;
    up.ExpirePasswordNow();
    up.Save();
  }
}

这会在域中创建用户,而不是在本地计算机上,这并不是我真正需要的。不过,谢谢。“如果不硬编码机器名称(将来可能会更改),我如何防止这种情况?”如果您知道如何在硬编码机器名称时进行此操作,那么使用System.Environment.MachineName来获取机器名称而不是硬编码如何?使用
new PrincipalContext(ContextType.Machine,Environment.MachineName)
给出的结果与只调用
新PrincipalContext(ContextType.Machine)
相同。