【C#代码】使用C#为AD添加用户

开发原因:

测试为什么在真是环境中取数据慢的问题。结论:绝对不是数据量的事情,可能是AD服务器不在本地的原因。

代码:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.DirectoryServices.AccountManagement;

namespace ADADD
{
    class Program
    {
        private static string stringDomainName = System.Net.NetworkInformation.IPGlobalProperties.GetIPGlobalProperties().DomainName;
        static void Main(string[] args)
        {
            
            for (int i = 0; i < 10000; i++)
            {
                bool b = CreateUser("wang", "yang", "yixiaozi"+i.ToString(), "00"+i.ToString(), "@foxmail.com", "1232313", "beijing,chaoyang");
            }
        }

        internal static bool CreateUser(string firstName, string lastName, string userLogonName, string employeeID, string emailAddress, string telephone, string address)
        {
            PrincipalContext PrincipalContext1 = new PrincipalContext(ContextType.Domain, stringDomainName);

            UserPrincipal usr = UserPrincipal.FindByIdentity(PrincipalContext1, userLogonName);
            if (usr != null)
            {
                return false;
            }

            // Create the new UserPrincipal object
            UserPrincipal userPrincipal = new UserPrincipal(PrincipalContext1);

            if (lastName != null && lastName.Length > 0)
                userPrincipal.Surname = lastName;

            if (firstName != null && firstName.Length > 0)
                userPrincipal.GivenName = firstName;

            if (employeeID != null && employeeID.Length > 0)
                userPrincipal.EmployeeId = employeeID;

            if (emailAddress != null && emailAddress.Length > 0)
                userPrincipal.EmailAddress = emailAddress;

            if (telephone != null && telephone.Length > 0)
                userPrincipal.VoiceTelephoneNumber = telephone;

            if (userLogonName != null && userLogonName.Length > 0)
                userPrincipal.SamAccountName = userLogonName;

            userPrincipal.SetPassword("a");

            userPrincipal.Enabled = true;
            userPrincipal.ExpirePasswordNow();

            try
            {
                userPrincipal.Save();
            }
            catch (Exception e)
            {
                return false;
            }
            return true;
        }


    }
}

如果不愿意编译,可以直接下载执行文件,不过测试完后删除的代码就需要自己写喽。

http://files.cnblogs.com/files/yixiaozi/ADADD.zip