ChangePassword method may fail with TargetInvocationException (.NET)


Hi all, welcome back,


When working with System.DirectoryServices.DirectoryEntry in .NET, we may change the password of the user with a code like the following (C#):

user.Invoke(“ChangePassword”, new object[] { oldPassword, newPassword }

But invoking ChangePassword may fail with the following System.Reflection.TargetInvocationException:


“Exception has been thrown by the target of an invocation”


This error is not very descriptive, I know. I’ve seen several causes for this error in the past:


1) Any of the passwords is incorrect.


2) The new password doesn’t meet the domain complexity requirements.


3) Minimum Password Age is > 0.


4) WinNT provider is used instead of LDAP.


 


By using InnerException.ToString() from the TargetInvocationException we may get a more descriptive error message. We could even see the HResult value associated to the exception. But this property is protected, so we could try to parse it from the error message string, with a code like this:

string errorMessage;
Int32 errorCode = 0;
try
{

}
catch (TargetInvocationException e)
{
errorMessage = e.InnerException.ToString();
try
{
string HResult = errorMessage.Substring(errorMessage.IndexOf(“0x”) + 2, 8);
errorCode = Int32.Parse(HResult, System.Globalization.NumberStyles.HexNumber);
}
catch
{
errorCode = -1;
}
}

 


I hope this helps.


Cheers,


 


Alex (Alejandro Campos Magencio)

Comments (3)

  1. Fran says:

    Thanks Alex for these cool scripts, we keep tuned

    Regards, ele,

    fran

  2. SC Vinod says:

    Hi Alex,

    Thanks for the code, very helpful. Can you also tell me what can be done with the HRESULT value that you retrieve in your code? Thanks once again.

  3. alejacma says:

    You may look for the HRESULT on the Internet (e.g. MSDN, Microsoft KB, etc) for more info on the error.