1

I’m using System.DirectoryServices.AccountManagement library to validate a local user.

I’ve got the following code:

  private bool IsValidWindowsUser(string userName, string password)
  {
       using (var p = new PrincipalContext(ContextType.Machine))
            return p.ValidateCredentials(userName, password);
  }

But whenever I am passing correct username with ".\" preappend e.g if the user is name is "test" and if I am passing username like ".\test" then it is giving me an exception

The network path was not found.

Can somebody please help me. If I remove ".\" then it is working fine.

My another condition is I only want to validate Local machine user not domain user.

Please help

2 Answers2

0

Try this:

p.ValidateCredentials(Environment.MachineName + "\\" + userName, password);
alex.b
  • 4,547
  • 1
  • 31
  • 52
0

Here's what I got working, in case someone else is having similar issue.

 string GetLogin(string s)
    {
        string regex = @"^(.*\\)?([^\@]*)(@.*)?$";
        return Regex.Replace(s, regex, "$2", RegexOptions.None);
    }

using (PrincipalContext pcLocal = new PrincipalContext(ContextType.Machine))
            {
                try
                {
                            try
                            {
                                if (null != group && pcLocal.ValidateCredentials($".\\{username}", password))
                                {
                                    return GetLogin(findByIdentity.SamAccountName);
                                }
                            }
                            catch (Exception)
                            {
                                string user = GetLogin(username);

                                if (null != group && pcLocal.ValidateCredentials(user, password))
                                {
                                    return GetLogin(findByIdentity.SamAccountName);
                                }
                            }

                }
                catch (Exception e)
                {
                    throw e;
                }
            }
Manny
  • 1,034
  • 1
  • 11
  • 16