Search code examples
c#active-directorydirectoryservices

help with finding user using directory service account management


I'm having an issue when trying to pass the value into the method via a parameter (userName). If I hard code the value, it will find the user.

Any guidance would be greatly appreciated,

protected void btnSubmit_Click(object sender, EventArgs e)
{
   if (!String.IsNullOrEmpty(txtUserName.Text))
   {
      string userName = txtUserName.ToString();

      PrincipalContext ctx = new PrincipalContext(ContextType.Domain, "car2.local", "DC=car2,DC=local");
      UserPrincipal usr = UserPrincipal.FindByIdentity(ctx, IdentityType.SamAccountName, userName);

      if(usr != null)
      {
         lblStatus.Text = "user exists";
      }
      else
      {
         lblStatus.Text = "user does not exists";
      }
   }
}

Solution

  • Try this - read out the .Text property of your textbox (and call .Trim() to get rid of any additional, superfluous whitespace) instead of using .ToString() on it:

    string userName = txtUserName.Text.Trim();
    
    UserPrincipal usr = UserPrincipal.FindByIdentity(ctx, userName);
    

    If you don't specify what type of identity to search for - then AD will search for the most common identity types and hopefully find your user!