C#: code error while changing the active directory user's password

后端 未结 3 995
既然无缘
既然无缘 2021-01-23 23:22
C# code     

> error--->>>Unknown name. (Exception from HRESULT: 0x80020006
> (DISP_E_UNKNOWNNAME))

and the code is this



        
3条回答
  •  深忆病人
    2021-01-23 23:44

    Simply follow the code under

    using System.DirectoryServices;
    
    
    private DirectoryEntry GetUser(string UserName)
    
    {
    
        DirectoryEntry de = GetDirectoryObject();
        DirectorySearcher deSearch = new DirectorySearcher();
        deSearch.SearchRoot = de;
    
        deSearch.Filter = "(&(objectClass=user)(SAMAccountName=" + UserName + "))";
        deSearch.SearchScope = SearchScope.Subtree;
        SearchResult results = deSearch.FindOne();
    
        if (!(results == null))
        {
           // **THIS IS THE MOST IMPORTANT LINE**
           de = new DirectoryEntry(results.Path, "username", "password", AuthenticationTypes.Secure); 
           return de;
        }
        else
        {
           return null;
        }
    }
    
    private DirectoryEntry GetDirectoryObject()
    
    {
    
        DirectoryEntry oDE;
        oDE = new DirectoryEntry("LDAP://192.168.1.101", "username", "password", AuthenticationTypes.Secure);
        return oDE;
    }
    
    
     public static bool ChangePassword(string UserName, string strOldPassword, string strNewPassword)
    
            {
    
                bool passwordChanged = false;
    
                DirectoryEntry oDE = GetUser(UserName, strOldPassword);
    
                if (oDE != null)
                {
                    try
                    {
                        // Change the password.
                        oDE.Invoke("ChangePassword", new object[] { strOldPassword, strNewPassword });
                        passwordChanged = true;
                    }
                    catch (Exception ex)
                    {
                        Debug.WriteLine("Error changing password. Reason: " + ex.Message);
    
                    }
                }
                return passwordChanged;
            }
    

提交回复
热议问题