首页 > 解决方案 > Windows 在所有情况下以编程方式创建用户

问题描述

我想用一个程序(C#,.net 4.5)创建一个用户:

String Domain =  System.Net.NetworkInformation.IPGlobalProperties.GetIPGlobalProperties().DomainName;
...
using (PrincipalContext pc = new PrincipalContext(ContextType.Domain, Domain))
{
    if (UserPrincipal.FindByIdentity(pc, IdentityType.UserPrincipalName, USER) != null)
    {
        .. error message ..
    ...

至少,这适用于域。但是创建本地用户(在属于域的计算机或独立计算机上创建)不起作用(执行用户是管理员 - 手动添加用户有效)。

我试图将域名设置为

但后来我在FindByIdentity收到以下错误消息:

System.DirectoryServices.AccountManagement.PrincipalServerDownException: 
Mit dem Server konnte keine Verbindung hergestellt werden. ---> 
System.DirectoryServices.Protocols.LdapException: Der LDAP-Server ist nicht verfügbar.

(德语,我添加了换行符) 粗略翻译:“无法连接到服务器 -> LDAP 服务器不可访问。”

我还将PrincipalContext更改为

using (PrincipalContext pc = new PrincipalContext(ContextType.Machine, Domain))

(并如上所述测试了所有域)。然后我在FindByIdentity收到以下错误消息:

System.IO.FileNotFoundException: Der Netzwerkpfad wurde nicht gefunden.

(德语)粗略翻译:“找不到网络路径”。

(所有测试均在 Windows 10(在域中)和“干净”的无域 Windows 7 上进行。)

我能做些什么来使它工作并且在所有情况下都只有一个代码路径。

(提示我还测试了从 PrincipalContext 中删除域名并将其添加到用户“@”+域。)

编辑

using (PrincipalContext pc = new PrincipalContext(ContextType.Machine))
{
    if (UserPrincipal.FindByIdentity(pc, IdentityType.SamAccountName, USER) != null)
    {
        .. error message ..
    ...

适用于非域机器上的本地访问。

标签: .netwinapiactive-directory

解决方案


根据要求,我当前的代码在本地或域中创建用户:

static internal bool CreateUser(String Domain, out String UserName, out String Pwd, out String error)
{
    bool localhost = (String.IsNullOrWhiteSpace(Domain) || Domain.Trim().Equals("localhost", StringComparison.InvariantCultureIgnoreCase) || Domain.Trim().StartsWith("127.") || Domain.Trim().Equals(System.Net.NetworkInformation.IPGlobalProperties.GetIPGlobalProperties().HostName.Trim(), StringComparison.InvariantCultureIgnoreCase));
    Console.WriteLine("Domain: " + Domain + (localhost ? " (localhost)" : ""));

    UserName = null;
    Pwd = null;
    try
    {
        ContextType cType = localhost ? ContextType.Machine : ContextType.Domain;
        Domain = localhost ? null : Domain;
        IdentityType iType = localhost ? IdentityType.SamAccountName : IdentityType.UserPrincipalName;

        using (PrincipalContext pc = new PrincipalContext(cType, Domain))
        {
            // Search for an non existent User
            int nr = 0;
            while (UserPrincipal.FindByIdentity(pc, iType, USER + (nr > 0 ? "" + nr : "")) != null) 
            {
                nr++;
                if (nr > 1000)
                {
                    error = "Could not create a user name - all possible names are in use. Please delete unnessesary users.";
                    return false;
                }
            } 

            UserName = USER + (nr > 0 ? "" + nr : "");
            Pwd = Membership.GeneratePassword(64, 8);

            String desciption = "User for bla!"

            using (UserPrincipal up = new UserPrincipal(pc))
            {
                up.SamAccountName = UserName;
                if (!localhost)
                {
                    up.GivenName = UserName;
                    up.UserPrincipalName = UserName;
                }
                up.DisplayName = "User";
                up.Description = desciption;
                up.SetPassword(Pwd);
                up.Enabled = true;
                up.UserCannotChangePassword = true;
                up.PasswordNeverExpires = true;
                up.Save();
            }

            int max = 600;
            // Now Wait until User is known
            while (UserPrincipal.FindByIdentity(pc, iType, UserName) == null)
            {
                Thread.Sleep(100);
                if (max-- <= 0)
                {
                    error = "User was not created in wait time.";
                    return false;
                }
            }
        }
        error = null;
        return true;
    }
    /*catch (PrincipalExistsException)
    {
        // Should not happen now
        error = null;
        return false;
    }*/
    catch (UnauthorizedAccessException e)
    {
        error = "Executeing user has insufficent permissions. Need the permission to create user in the domain: \"" + Domain + "\":\n" + e;
        return false;
    }
    catch (Exception e)
    {
        error = e.ToString();
        return false;
    }
}

希望这可以帮助一两个人..


推荐阅读