首页 > 代码库 > .net操作AD域

.net操作AD域

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Configuration;
using System.DirectoryServices;
namespace OperateADLibrary
{
    public class OperateAD
    {
        /// <summary>
        /// 域名
        /// </summary>
        private string _domain;
        /// <summary>
        /// 主机域IP
        /// </summary>
        private string _domainIp;
        /// <summary>
        /// 管理员账号
        /// </summary>
        private string adminUser;
        /// <summary>
        /// 管理员密码
        /// </summary>
        private string adminPwd;
        /// <summary>
        /// 路径的最前端
        /// </summary>
        private string _ldapIdentity;
        /// <summary>
        /// 路径的最后端
        /// </summary>
        private string _suffixPath;
        #region 构造函数
        /// <summary>
        /// 构造函数
        /// 从webConfig的AppSettings属性读取值初始化字段
        /// </summary>
        public OperateAD(string domain, string domainIp, string adUser, string adPwd)
        {
            //_domain = System.Configuration.ConfigurationManager.AppSettings["Domain"].ToString();
            //_domainIp = System.Configuration.ConfigurationManager.AppSettings["DomainIp"].ToString();
            //adminUser = System.Configuration.ConfigurationManager.AppSettings["ADAdminUser"].ToString();
            //adminPwd = System.Configuration.ConfigurationManager.AppSettings["ADAdminPassword"].ToString();
            //_ldapIdentity = "LDAP://" + _domainIp + "/";
            //_suffixPath = "DC=" + _domain + ",DC=COM";
            //_domain = "bdxy";
            //_domainIp = "10.1.209.197";
            //adminUser = "administrator";
            //adminPwd = "123456";
            _domain = domain;
            _domainIp = domainIp;
            adminUser = adUser;
            adminPwd = adPwd;
            _ldapIdentity = "LDAP://" + _domainIp + "/";
            _suffixPath = "DC=" + _domain + ",DC=com";
        }
        #endregion
        #region 组织结构下添加AD账户
        /// <summary>
        /// 添加AD账户
        /// </summary>
        /// <param name="organizeName">组织名称</param>
        /// <param name="user">域账户</param>
        /// <returns>添加是否成功</returns>
        public bool AddADAccount(string organizeName, DomainUser user)
        {
            DirectoryEntry entry = null;
            try
            {
                if (ExitOU(organizeName) && user != null)
                {
                    entry = new DirectoryEntry(GetOrganizeNamePath(organizeName), adminUser, adminPwd, AuthenticationTypes.Secure);
                    //增加账户到域中
                    DirectoryEntry NewUser = entry.Children.Add("CN=" + user.UserName, "user");
                    NewUser.Properties["sAMAccountName"].Add(user.UserName); //account
                    NewUser.Properties["userPrincipalName"].Value = http://www.mamicode.com/user.UserPrincipalName; //user logon name,xxx@bdxy.com
                    NewUser.Properties["givenName"].Value = "http://www.mamicode.com/New User";//名
                    NewUser.Properties["initials"].Value = "http://www.mamicode.com/Ms";
                    NewUser.Properties["name"].Value = "http://www.mamicode.com/12";//full name
                    NewUser.Properties["sn"].Value = http://www.mamicode.com/user.UserId;
                    NewUser.Properties["displayName"].Value = http://www.mamicode.com/user.UserName;
                    NewUser.Properties["company"].Value = "http://www.mamicode.com/1234";
                    NewUser.Properties["physicalDeliveryOfficeName"].Value = http://www.mamicode.com/user.PhysicalDeliveryOfficeName;
                    NewUser.Properties["Department"].Value = http://www.mamicode.com/user.Department;
                    if (user.Telephone != null && user.Telephone != "")
                    {
                        NewUser.Properties["telephoneNumber"].Value = http://www.mamicode.com/user.Telephone;
                    }
                    if (user.Email != null && user.Email != "")
                    {
                        NewUser.Properties["mail"].Value = http://www.mamicode.com/user.Email;
                    }
                    if (user.Description != null && user.Description != "")
                    {
                        NewUser.Properties["description"].Value = http://www.mamicode.com/user.Description;
                    }
                    NewUser.CommitChanges();
                    //设置密码
                    //反射调用修改密码的方法(注意端口号的问题  端口号会引起方法调用异常)
                    NewUser.Invoke("SetPassword", new object[] { user.UserPwd });
                    //默认设置新增账户启用
                    NewUser.Properties["userAccountControl"].Value = http://www.mamicode.com/0x200;
                    NewUser.CommitChanges();
                    //DomainUser._success = "账户添加成功!";
                    return true;
                }
                else
                {
                    //DomainUser._failed = "在域中不存在直属组织单位";
                    return false;
                }
              
            }
            catch (System.DirectoryServices.DirectoryServicesCOMException ex)
            {
                //DomainUser._failed = "账户添加失败!"+ex.Message.ToString();
                return false;
            }
            finally
            {
                if (entry != null)
                {
                    entry.Dispose();
                }
            }
        }
        #endregion
        #region 重命名账户
        /// <summary>
        /// 重命名账户
        /// </summary>
        /// <param name="adminUser">管理员名称</param>
        /// <param name="adminPassword">管理员密码</param>
        /// <param name="oldUserName">原用户名</param>
        /// <param name="newUserName">新用户名</param>
        public bool RenameUser(string oldUserName, string newUserName)
        {
            try
            {
                DirectoryEntry userEntry = FindObject("user", oldUserName);
                if (userEntry != null)
                {
                    userEntry.Rename("CN="+newUserName);
                    userEntry.CommitChanges();
                    //DomainUser._success = "重命名成功!";
                    return true;
                }
                //DomainUser._failed = "没找到用户!" + oldUserName;
                return false;
            }
            catch (Exception ex)
            {
                //DomainUser._failed = "重命名失败!"+ex.Message.ToString();
                return false;
            }
        }
        #endregion
        #region 设置用户密码
        /// <summary>
        /// 设置用户密码
        /// </summary>
        /// <param name="userName">用户名</param>
        /// <param name="password">密码</param>
        public bool SetUserPassword(string userName, string password)
        {
            try
            {
                DirectoryEntry userEntry = FindObject("user", userName);
                if (userEntry != null)
                {
                    userEntry.Invoke("SetPassword", new object[] { password });
                    userEntry.CommitChanges();
                    //DomainUser._success = "密码设置成功!";
                    return true;
                }
                //DomainUser._failed = "没找到用户!" + userName;
                return false;
            }
            catch (Exception ex)
            {
                //DomainUser._failed = "密码设置失败!"+ex.Message.ToString();
                return false;
            }
        }
        #endregion
        #region 修改密码
        /// <summary>
        /// 修改密码
        /// </summary>
        /// <param name="ude">用户</param>
        /// <param name="password">旧密码</param>
        /// <param name="password">新密码</param>
        public  bool ChangePassword(string username, string oldpwd, string newpwd)
        {
            try
            {
                DirectoryEntry entry = FindObject("user", username);
                if (entry != null)
                {
                    // to-do: 需要解决密码策略问题
                    entry.Invoke("ChangePassword", new object[] {oldpwd, newpwd });
                    entry.CommitChanges();
                    entry.Close();
                   // DomainUser._success = "密码修改成功!";
                    return true;
                }
                else
                {
                   // DomainUser._failed = "没找到用户!" + username;
                    return false;
                }
            }
            catch (Exception ex)
            {
                //DomainUser._failed = "密码修改失败!"+ex.Message.ToString();
                return false;
            }
        }
        #endregion
        #region 删除账户
        /// <summary>
        /// 删除AD账户,使用当前上下文的安全信息
        /// </summary>
        /// <param name="userName">用户名称</param>
        public bool DeleteADAccount(string userName)
        {
            try
            {
                DirectoryEntry user = FindObject("user", userName);
                if (user != null)
                {
                    using (DirectoryEntry de = new DirectoryEntry(user.Parent.Path, adminUser, adminPwd))
                    {
                        de.Children.Remove(user);
                        de.CommitChanges();
                        //DomainUser._success = "账户删除成功!";
                        return true;
                    }
                }
               // DomainUser._failed = "未找到账户!";
                return false;
            }
            catch (Exception ex)
            {
                //DomainUser._failed = "账户删除失败!" + ex.Message.ToString();
                return false;
            }
        }
        #endregion

转载:http://www.cnblogs.com/VicHuang/p/3753555.html