【问题标题】:create AD-User in c#在 C# 中创建 AD 用户
【发布时间】:2013-07-03 12:01:44
【问题描述】:

我正在尝试使用此代码创建一个新的 AD 用户:

PrincipalContext ctx = new PrincipalContext(ContextType.Domain, "Domain", "ou=some_ou, dc=Mydomain");
UserPrincipal user = new UserPrincipal(ctx, account, passwd, true);
user.GivenName = Givenname;
user.Surname = Surname;
user.DisplayName = Displayname;
user.UserPrincipalName = account + "@Domain";                
user.Save();

用户的创建没有错误。但我还必须设置地址等属性,所以代码继续:

string distname = user.DistinguishedName;
DirectoryEntry duser = new DirectoryEntry(distname);
try
{
    duser.Properties["company"].Value = "Company";
}
catch (Exception e)
{
}

现在我明白了

错误:System.Exception._COMPlusExceptionCode -532459699

字符串distname 显示正确的专有名称。

【问题讨论】:

  • 你能试试this吗?它应该让您对正在抛出的异常有另一种看法。它可能比代码提供更多信息。
  • 异常发生在哪一行,这个新的目录条目代码是在您调用user.Save()之前还是之后发生的?

标签: c# .net active-directory


【解决方案1】:

我不是 100% 确定是什么导致了您的问题,但由于您同时使用 DirectoryServicesDirectoryServices.AccountManagement 不正确,一件事可能会让您的事情变得更轻松,并且可能会清除一些错误是 @987654321 @。

其实并不难。

[DirectoryObjectClass("user")]
[DirectoryRdnPrefix("CN")]
public class UserPrincipalEx : UserPrincipal
{
    public UserPrincipalEx(PrincipalContext context) : base(context) { }

    public UserPrincipalEx(PrincipalContext context, string samAccountName, string password, bool enabled)
        : base(context, samAccountName, password, enabled)
    {
    }

    [DirectoryProperty("company")]
    public string Company
    {
        get
        {
            if (ExtensionGet("company").Length != 1)
                return null;

            return (string)ExtensionGet("company")[0];

        }
        set { this.ExtensionSet("company", value); }
    }
}

然后您可以将代码修改为

PrincipalContext ctx = new PrincipalContext(ContextType.Domain, "Domain", "ou=some_ou, dc=Mydomain");
UserPrincipalEx user = new UserPrincipalEx(ctx, account, passwd, true);
user.GivenName = Givenname;
user.Surname = Surname;
user.DisplayName = Displayname;
user.UserPrincipalName = account + "@Domain"; 
user.Company = "Company";
user.Save();

我的预感是您正在与与 Active Directory 交互的两种方法进行某种交互,如果您切换到单个界面,您的问题可能就会消失。

【讨论】:

    【解决方案2】:

    对于 DirectoryEntry,您必须指定协议(LDAP、GC、WinNT、...)。所以你必须这样做:

    DirectoryEntry duser = new DirectoryEntry("LDAP://" + distname);
    

    请注意,协议区分大小写,LDAP 必须全部大写。

    【讨论】:

      【解决方案3】:

      我看到您在 UserPrincipal 中使用凭据,

      您在创建 DirectoryEntry 时是否忘记使用它们? 另外,您需要在服务器名称前添加“LDAP://”

      试试类似的东西:

      DirectoryEntry duser = new DirectoryEntry("LDAP://" + distname);
      duser.Username = account;
      duser.Password = passwd;
      duser.AuthenticationType = AuthenticationTypes.Secure; 
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2019-08-10
        • 1970-01-01
        • 2016-08-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多