How can I determine if a Windows Identity corresponds to a local or a domain user?

后端 未结 2 970
醉酒成梦
醉酒成梦 2021-02-06 16:22

I have a WindowsIdentity, which corresponds to an authenticated user. How can I determine if the identity corresponds to a Local User on the machine, a domain user who has been

2条回答
  •  清酒与你
    2021-02-06 16:43

    Assuming WindowsIdentity.Name works like Environment.UserDomainName, if the user name begins with the machine name then it's not on the domain otherwise it is on the domain. This allows you to write

    public static bool IsDomain(WindowsIdentity identity)
    {
        string prefix = identity.Name.Split('\\')[0];
        if (prefix != Environment.MachineName)
            return true;
        else
            return false;
    }
    

    The UserDomainName property first attempts to get the domain name component of the Windows account name for the current user. If that attempt fails, this property attempts to get the domain name associated with the user name provided by the UserName property. If that attempt fails because the host computer is not joined to a domain, then the host computer name is returned.

    You may also filter against a list of available domains (e.g. stored in a DB) for the edge case that a computer name and the domain name are the same.

提交回复
热议问题