Decrypt my World

Cryptography, Security, Debugging and more!

ChangePassword method may fail with TargetInvocationException (.NET)

ChangePassword method may fail with TargetInvocationException (.NET)

  • Comments 3

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)

  • Thanks Alex for these cool scripts, we keep tuned

    Regards, ele,

    fran

  • 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.

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

Page 1 of 1 (3 items)
Leave a Comment
  • Please add 6 and 7 and type the answer here:
  • Post
Translate This Page