愚见未来

人的思想时时刻刻都在进步,如果你早上起床,想起昨天所做的事情是那么幼稚和迂腐,那么恭喜你,你又变得成熟一点了!
  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

C# 操作Windows域代码

Posted on 2009-12-25 12:01  愚见未来  阅读(1476)  评论(1编辑  收藏  举报

前段时间研究了LDAP用户集成的一些内容,下面是我经过多次google后,自己写的一份操作Windows域的代码,

这是操作domain的类:

  private string _Domain;
    private string AdUser;
    private string AdPwd;
    private string _prefixPath = "LDAP://";
    private string _suffixPath;
 public OperateDomain()
 {
        _Domain = System.Configuration.ConfigurationManager.AppSettings["Domain"].ToString();
        AdUser = System.Configuration.ConfigurationManager.AppSettings["ADAdminUser"].ToString();
        AdPwd = System.Configuration.ConfigurationManager.AppSettings["ADAdminPassword"].ToString();
        _suffixPath = "DC=" + _Domain + ",DC=COM";
 }

/// <summary>
    /// 添加用户
    /// </summary>
    /// <param name="directoryType">父节点的类型</param>
    /// <param name="parentNode">父节点名称</param>
    /// <param name="user">用户</param>
    /// <returns></returns>
    private string AdAddUser( DomainUser user)
    {
        string path = FormatPath(DomainUser._cn, "users");
        try
        {
            DirectoryEntry Entry = new DirectoryEntry(path, AdUser, AdPwd, AuthenticationTypes.Secure);
            DirectoryEntry NewUser = Entry.Children.Add("cn=" + user.UserId, "User");

            NewUser.Properties["userPrincipalName"].Value = user.UserPrincipalName;
            NewUser.Properties["name"].Value = user.UserId;
            NewUser.Properties["sn"].Value = user.UserId;
            NewUser.Properties["displayName"].Value = user.UserName;
            NewUser.Properties["samAccountName"].Value = user.UserId;
            NewUser.Properties["Department"].Value = user.Department;
            //NewUser.Properties["telephoneNumber"].Value = user.Telephone;
            //NewUser.Properties["mail"].Value = user.Email;
            if (user.Telephone != null && user.Telephone != "")
            {
                NewUser.Properties["telephoneNumber"].Value = user.Telephone;
            }
            //else
            //{
            //    NewUser.Properties["telephoneNumber"].Value = null;
            //}
            if (user.Email != null && user.Email != "")
            {
                NewUser.Properties["mail"].Value = user.Email;
            }
            //else
            //{
            //    NewUser.Properties["mail"].Value = null;
            //}
            if (user.Description != null && user.Description != "")
            {
                NewUser.Properties["description"].Value = user.Description;
            }
            //else
            //{
            //    NewUser.Properties["description"].Value = null;

            //}
            NewUser.CommitChanges();

            SetAdPassword(user.UserId, user.Password);
            EnableUser(user.UserId);
            Entry.Close();

            return DomainUser._success;
        }
        catch (Exception ex)
        {
            LogManage.SaveInfo(ex.ToString());
            return DomainUser._failed;
        }
    }
    /// <summary>
    /// 修改帐户信息
    /// </summary>
    /// <param name="user"></param>
    /// <returns></returns>
    private string ModifyADUser(DomainUser user)
    {
        try
        {
            DirectoryEntry dEntry = GetUser(user.UserId);
            DirectoryEntry Entry = new DirectoryEntry(dEntry.Path, AdUser, AdPwd, AuthenticationTypes.Secure);

            Entry.Properties["displayName"].Value = user.UserName;
            Entry.Properties["Department"].Value = user.Department;

            if (user.Telephone != null && user.Telephone != "")
            {
                Entry.Properties["telephoneNumber"].Value = user.Telephone;
            }
            else
            {
                Entry.Properties["telephoneNumber"].Value = null;
            }
            if (user.Email != null && user.Email != "")
            {
                Entry.Properties["mail"].Value = user.Email;
            }
            else
            {
                Entry.Properties["mail"].Value = null;
            }
            if (user.Description != null && user.Description != "")
            {
                Entry.Properties["description"].Value = user.Description;
            }
            else
            {
                Entry.Properties["description"].Value = null;

            }

            Entry.CommitChanges();
            Entry.Close();
            dEntry.Close();
            return DomainUser._success;
        }
        catch (Exception ex)
        {
            LogManage.SaveInfo(ex.ToString());
            return DomainUser._failed;
        }
    }
    /// <summary>
    /// 判断用户帐号是否激活
    /// </summary>
    /// <param name="username"></param>
    /// <returns>如果用户帐号已经激活,返回 true;否则返回 false</returns>
    public string IsAccountActive(string username)  
     {
        try
        {
            DirectoryEntry de = GetUser(username);
             int userAccountControl = Convert.ToInt32(de.Properties["userAccountControl"][0]);
             int userAccountControl_Disabled = Convert.ToInt32(ActiveDs.ADS_USER_FLAG.ADS_UF_ACCOUNTDISABLE);
             int flagExists = userAccountControl & userAccountControl_Disabled;

             if (flagExists > 0)
                 return LoginResult.LOGIN_USER_ACCOUNT_INACTIVE.ToString();
             else
                 return LoginResult.LOGIN_USER_ACCOUNT_ACTIVE.ToString();
         }
        catch(Exception ex)
        {
            LogManage.SaveInfo(ex.ToString());
            return ex.ToString();
        }
    }
    /// <summary>
    /// 开启用户
    /// </summary>
    /// <param name="user"></param>
    private string EnableUser(string username)
    {
        try
        {
            DirectoryEntry user = GetUser(username);
            int val = (int)user.Properties["userAccountControl"].Value;
            //用户密码永不过期
            user.Properties["userAccountControl"].Value = val & ~(int)ActiveDs.ADS_USER_FLAG.ADS_UF_ACCOUNTDISABLE | (int)ActiveDs.ADS_USER_FLAG.ADS_UF_DONT_EXPIRE_PASSWD;
            user.CommitChanges();
            user.Close();
            return DomainUser._success;

        }
        catch (Exception ex)
        {
            LogManage.SaveInfo(ex.ToString());
            return DomainUser._failed;

        }
    }
    /// <summary>
    /// 禁用/激活用户
    /// </summary>
    /// <param name="username"></param>
    private string UnenableUser(string username)
    {
        try
        {
            DirectoryEntry user = GetUser(username);
            int val = (int)user.Properties["userAccountControl"].Value;
            user.Properties["userAccountControl"].Value = val | (int)ActiveDs.ADS_USER_FLAG.ADS_UF_ACCOUNTDISABLE;

            user.CommitChanges();
            user.Close();
            return DomainUser._success;

        }
        catch (Exception ex)
        {
            LogManage.SaveInfo(ex.ToString());
            return DomainUser._failed;

        }
    }
    /// <summary>
    /// 设置密码
    /// </summary>
    /// <param name="ude">用户</param>
    /// <param name="password">密码</param>
    private string SetAdPassword(string username, string password)
    {
        try
        {
            DirectoryEntry entry = GetUser(username);
            entry.Invoke("SetPassword", new object[] { password });
            entry.CommitChanges();
            entry.Close();
            return DomainUser._success;

        }
        catch (Exception ex)
        {
            LogManage.SaveInfo(ex.ToString());
            return DomainUser._failed;

        }
    }
    /// <summary>
    /// 修改密码
    /// </summary>
    /// <param name="ude">用户</param>
    /// <param name="password">旧密码</param>
    /// <param name="password">新密码</param>
    private string ChangePassword(string username, string oldpwd, string newpwd)
    {
        try
        {
            DirectoryEntry entry = GetUser(username);
           
            entry.Invoke("ChangePassword", new object[] { oldpwd, newpwd });
            entry.CommitChanges();
            entry.Close();
            return DomainUser._success;
        }
        catch (Exception ex)
        {
            LogManage.SaveInfo(ex.ToString());
            return DomainUser._failed;
        }
    }
    /// <summary>
    /// 格式化要添加的对象是否存在的DirectoryEntry的参数Path
    /// </summary>
    /// <param name="addType">对象的类型(组织单位/组/计算机/联系人)</param>
    /// <param name="directoryType">父节点的类型</param>
    /// <param name="parentNode">父节点名称</param>
    /// <param name="ouName">节点名称</param>
    /// <returns></returns>
    private string FormatPath(string addType, string directoryType, string parentNode, string ouName)
    {
        string path = "";
        //返回存在组织单位的path
        if (addType == DomainUser._ou)
        {
            //在组织单位下面
            if (directoryType == DomainUser._ou)
            {
                path = _prefixPath + "OU=" + ouName + "," + "OU=" + parentNode + "," + _suffixPath;
            }
            //在域下面
            else
            {
                path = _prefixPath + "OU=" + ouName + "," + _suffixPath;
            }
            return path;
        }
        //返回存在(组/计算机/联系人)的path
        else if (addType == DomainUser._cn)
        {
            //在组织单位下面
            if (directoryType == DomainUser._ou)
            {
                path = _prefixPath + "CN=" + ouName + "," + "OU=" + parentNode + "," + _suffixPath;
            }
            //在文件夹下(Users)
            else if (directoryType == DomainUser._cn)
            {
                path = _prefixPath + "CN=" + ouName + "," + "CN=" + parentNode + "," + _suffixPath;
            }
            //在域下面
            else
            {
                path = _prefixPath + "CN=" + ouName + "," + _suffixPath;
            }
            return path;
        }
        else
        {
            return path;
        }
    }
    /// <summary>
    /// 格式化父节点DirectoryEntry的参数Path
    /// </summary>
    /// <param name="addType">添加对象的类型(组织单位/组/计算机/联系人)</param>
    /// <param name="directoryType">父节点的类型</param>
    /// <param name="parentNode">父节点名称</param>
    /// <returns></returns>
    private string FormatPath(string directoryType, string parentNode)
    {
        string path = "";
        ////返回组织单位的path
        //if (addType == DomainUser._ou)
        //{
        //    //在组织单位下面
        //    if (directoryType == DomainUser._ou)
        //    {
        //        path = _prefixPath + "OU=" + parentNode + "," + _suffixPath;
        //    }
        //    //在域下面
        //    else
        //    {
        //        path = _prefixPath + _suffixPath;
        //    }
        //    return path;
        //}
        //返回(组/计算机/联系人)的path
        //else if (addType == DomainUser._cn)
        //{
        //在组织单位下面
        if (directoryType == DomainUser._ou)
        {
            path = _prefixPath + "OU=" + parentNode + "," + _suffixPath;
        }
        //在文件夹下(Users)
        else if (directoryType == DomainUser._cn)
        {
            path = _prefixPath + "CN=" + parentNode + "," + _suffixPath;
        }
        //在域下面
        else
        {
            path = _prefixPath + _suffixPath;
        }
        return path;
        //}
        //else
        //{
        //    return path;
        //}
    }
    /// <summary>
    /// 从域中按照用户名查找用户
    /// </summary>
    /// <param name="username"></param>
    /// <returns></returns>
    private DirectoryEntry GetUser(string username)
    {
        string path = _prefixPath + _suffixPath;
        DirectoryEntry deuser;
        try
        {
            DirectoryEntry de = new DirectoryEntry(path, AdUser, AdPwd);
            DirectorySearcher deSearch = new DirectorySearcher(de);
            deSearch.Filter = "(&(objectClass=user)(cn=" + username + "))";
            deSearch.SearchScope = SearchScope.Subtree;
            SearchResult result = deSearch.FindOne();
            if (result != null)
            {
                deuser = result.GetDirectoryEntry();
                return deuser;
            }
            else
            {
                return null;
            }
        }
        catch(Exception ex)
        {           
            LogManage.SaveInfo(ex.ToString());
            return null;
        }
    }
    /// <summary>
    /// 判断用户是否已经存在域中
    /// </summary>
    /// <param name="userId"></param>
    /// <returns></returns>
    private bool ExitUser(string userId)
    {
        try
        {
            DirectoryEntry de = null;
            de = GetUser(userId);
            if (de == null)
            {
                return false;
            }
            else
            {
                return true;
            }
        }
        catch(Exception ex)
        {
            LogManage.SaveInfo(ex.ToString());
            return true;
        }
    }
    /// <summary>
    /// 获取域用户信息
    /// </summary>
    /// <param name="userid"></param>
    /// <returns></returns>
    public DomainUser GetAdUserInfo(string userid)
    {
        DomainUser du = new DomainUser();
        DirectoryEntry de = GetUser(userid);
        if (de != null)
        {
            if (de.Properties["samAccountName"].Value != null)
            {
                du.UserId = de.Properties["samAccountName"].Value.ToString();
            }
            if (de.Properties["displayName"].Value != null)
            {
                du.UserName = de.Properties["displayName"].Value.ToString();
            }
            if (de.Properties["userPrincipalName"].Value != null)
            {
                du.UserPrincipalName = de.Properties["userPrincipalName"].Value.ToString();
            }
            if (de.Properties["telephoneNumber"].Value != null)
            {
                du.Telephone = de.Properties["telephoneNumber"].Value.ToString();
            }
            if (de.Properties["mail"].Value != null)
            {
                du.Email = de.Properties["mail"].Value.ToString();
            }
            if (de.Properties["description"].Value != null)
            {
                du.Description = de.Properties["description"].Value.ToString();
            }
            if (de.Properties["Department"].Value != null)
            {
                du.Department = de.Properties["Department"].Value.ToString();
            }
        }

        return du;       
    }
    /// <summary>
    /// 从域中删除用户
    /// </summary>
    /// <param name="du"></param>
    /// <returns></returns>
    public string DeleteUser(DomainUser du)
    {
        try
        {
            DirectoryEntry de = GetUser(du.UserId);
            if (de != null)
            {
                string path = de.Parent.Path;
                DirectoryEntry parentde = new DirectoryEntry(path, AdUser, AdPwd, AuthenticationTypes.Secure);
                parentde.Children.Remove(de);
                return DomainUser._success;
            }
            else
            {
                return DomainUser._failed;
            }
        }
        catch (Exception ex)
        {
            LogManage.SaveInfo(ex.ToString());
            return DomainUser._failed;
        }
    }