Raj
Raj

Reputation: 4010

using windows username password in C#

how i can use windows stored username and password in my C# APP. I am looking for method which returns bool state of successful login. means :

bool isCredentialValid = CheckLogin(username, password);

so according to bool value I can show proper message.

Updated

class Program
{
    static void Main(string[] args)
    {
        PrincipalContext pc = new PrincipalContext(ContextType.Machine);
        Console.WriteLine("Enter username : ");
        string user = Console.ReadLine();

        Console.WriteLine("Enter password : ");
        string pass = Console.ReadLine();

        bool isValid = pc.ValidateCredentials(user, pass);

        Console.WriteLine("State : {0}",isValid);

        Console.ReadLine();
    }
}

this code is not working. when i enable Guest account it shows true for every login and when i disable Guest account it does not verifies even existing account. Any help would be appreciated.

Upvotes: 5

Views: 16753

Answers (2)

PawanS
PawanS

Reputation: 7193

Add using System.Security.Principal;

//for current Username full
 string str = WindowsIdentity.GetCurrent().Name;

Then u can use this username for authentication. For password it is different.

Upvotes: 3

VinayC
VinayC

Reputation: 49185

Have a look at PrincipalContext.ValidateCredentials method. For example,

PrincipalContext pc = new PrincipalContext(ContextType.Domain);
bool isCredentialValid = pc.ValidateCredentials(username, password);

for local accounts, use ContextType.Machine.

Yet another way would be using win32 api LogonUser function

Upvotes: 10

Related Questions