The samAccountName IdentityType must be in the form “domainnameuserName”, “machinenameuserName”, or “userName”

Hi, I got this error ‘The samAccountName IdentityType must be in the form “domainnameuserName”, “machinenameuserName”, or “userName”‘ when trying to find user Identity by using its samAccountName.

public static void EnableUser(string domain,string userName)
{
   PrincipalContext ctx = new PrincipalContext(domain);

   UserPrincipal usr = UserPrincipal.FindByIdentity(ctx, IdentityType.SamAccountName, 
                                           userName);
  if(usr != null)
  {
    if (usr.Enabled == false)
        usr.Enabled = true;
        usr.Save();
  }
}

Solution: Error due to ‘Empty User Name’

After, I have analyzed some time found the issue due to Empty UserName. the user name was wrongly sent as empty string from other part of the code. You will get the same error when run the below code.

PrincipalContext ctx = new PrincipalContext("yourdomain");

UserPrincipal usr = UserPrincipal.FindByIdentity(ctx, IdentityType.SamAccountName, "");

Thanks
Morgan
Software Developer


Advertisement

Leave a Comment