Reputation: 977
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
Upvotes: 1
Views: 2180
Reputation: 1034
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;
}
}
Upvotes: 0
Reputation: 4567
Try this:
p.ValidateCredentials(Environment.MachineName + "\\" + userName, password);
Upvotes: 0