Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/windows/16.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 如何检查当前PC用户是否为当前登录用户?_C#_Windows - Fatal编程技术网

C# 如何检查当前PC用户是否为当前登录用户?

C# 如何检查当前PC用户是否为当前登录用户?,c#,windows,C#,Windows,出于安全原因,我们希望检查当前PC用户是否是实际登录的用户。为此,我们希望用户重新输入他们的密码,并在域中检查他的凭据。我们如何才能做到这一点 到目前为止,我们尝试了以下方法: public static Boolean Authenticate(String password) { String user = WindowsIdentity.GetCurrent().Name; using (PrincipalContext PrincipalContext = new P

出于安全原因,我们希望检查当前PC用户是否是实际登录的用户。为此,我们希望用户重新输入他们的密码,并在域中检查他的凭据。我们如何才能做到这一点

到目前为止,我们尝试了以下方法:

public static Boolean Authenticate(String password)
{
    String user = WindowsIdentity.GetCurrent().Name; 

    using (PrincipalContext PrincipalContext = new PrincipalContext(ContextType.Domain, Environment.UserDomainName))
    {
        return PrincipalContext.ValidateCredentials(user, password);
    }
}
但是获取一个
System.DirectoryServices.Protocols.ldapeException
,将
环境.UserDomainName
关闭也会触发此异常

我们还尝试:

public static Boolean Authenticate(String password)
{
    String user = WindowsIdentity.GetCurrent().Name; 

    using (PrincipalContext PrincipalContext = new PrincipalContext(ContextType.Machine))
    {
        return PrincipalContext.ValidateCredentials(user, password);
    }
}

但这在任何密码上都是真的。

经过一些搜索后,我发现。原来域名包含在
WindowsIdentity.GetCurrent().name
中。如表中的备注所示

将此作为工作解决方案:

public static Boolean Authenticate(String password)
{
    String user = WindowsIdentity.GetCurrent().Name; //Should be: DomainName\UserName
    String[] DomainAndUserName = user.Split(new Char[] { '\\' }, 2);

    if (DomainAndUserName.Length != 2) { return false; } // No DomainName ==> Wrong network;

    using (PrincipalContext PrincipalContext = new PrincipalContext(ContextType.Domain, DomainAndUserName[0]))
    {
            return PrincipalContext.ValidateCredentials(DomainAndUserName[1], password);
    }
}