How to validate windows local users using c# ?

venkateswararao 21 Reputation points
2020-12-10T06:43:13.1+00:00

Hi,

I am using below code to validate but it is working for few users and it is not working for few users.please help me to resolve this issue.

public bool ValidatePassword(string userName, string Password, ref string errorMessage)
{
errorMessage = "";
PrincipalContext principalContext = null;
UserPrincipal userPrincipal = null;

            try
            {


                principalContext = new PrincipalContext(ContextType.Machine, null, null, userName, Password);

                userPrincipal = UserPrincipal.FindByIdentity(principalContext, userName);

                if (userPrincipal != null)
                {
                    userPrincipal.Dispose();
                    principalContext.Dispose();
                    return true;
                }
                else
                {
                    errorMessage = "Invalid user / password";
                    return false;
                }
            }
            catch (Exception ex)
            {

                if (userPrincipal != null)
                    userPrincipal.Dispose();

                if (principalContext != null)
                    principalContext.Dispose();

                errorMessage = ex.Message;
                System.Diagnostics.Debug.WriteLine("Error validate password: {0}", ex.Message);

                return false;
            }
        }

Thanks & regards,
Venkateswara rao

C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
10,906 questions
0 comments No comments
{count} votes

1 answer

Sort by: Most helpful
  1. Daniel Zhang-MSFT 9,626 Reputation points
    2020-12-11T02:52:17.003+00:00

    Hi venkateswararao-9381,
    First, I create three local users in User list of Computer Management window(Test, Test1,Test2).
    47183-12111.png
    And then made a test with your code example. They all returned true.
    So you need to check the differences of Users.
    What is error message returned when it doesn’t work? Could you provide more details?
    Meanwhile, when I created the user, I did not check the following checkboxes.
    47202-1211.png
    Best Regards,
    Daniel Zhang


    If the response is helpful, please click "Accept Answer" and upvote it.

    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.