检查用户是域用户或本地用户用户

2023-09-03 07:03:54 作者:畅聊往事

我希望能够检查给一个用户名,如果该用户是域用户或本地用户(使用.NET preferable)的机器,但可以发现很多关于这个在网络上

 公共静态布尔isLocalUser(字符串名称)
{
// code在这里
}
 

编辑 例如,您将得到me.user作为字符串

解决方案

 公共BOOL DoesUserExist(用户名字符串)
{
    布尔存在= FALSE;
    尝试
    {
    使用(VAR domainContext =新PrincipalContext(ContextType.Domain,域))
    {
        使用(VAR foundUser = UserPrincipal.FindByIdentity(domainContext,IdentityType.SamAccountName,用户名))
        {
            存在= TRUE;
        }
      }
    }
    赶上(例外前)
    {
      //如果机器是不是一个域可能会出现异常
    }
    使用(VAR domainContext =新PrincipalContext(ContextType.Machine))
    {
        使用(VAR foundUser = UserPrincipal.FindByIdentity(domainContext,IdentityType.SamAccountName,用户名))
        {
            存在= TRUE;
        }
    }
   返回的存在;
}
 

来源:Check使用C#在Active Directory用户名存在

批量查看域用户是否为本地管理员及查看本地管理员组成员

I want to be able to check giving a username if that user is a Domain User or a Local User (using .NET preferable) of the machine but could find much on this on the net

public static Boolean isLocalUser (string name)
{
//code here
}

EDIT for example you are given me.user as a string

解决方案

public bool DoesUserExist(string userName)
{
    bool exists = false;
    try
    {
    using (var domainContext = new PrincipalContext(ContextType.Domain, "DOMAIN"))
    {
        using (var foundUser = UserPrincipal.FindByIdentity(domainContext, IdentityType.SamAccountName, userName))
        {
            exists = true;
        }
      }
    }
    catch(exception ex)
    {
      //Exception could occur if machine is not on a domain
    } 
    using (var domainContext = new PrincipalContext(ContextType.Machine))
    {
        using (var foundUser = UserPrincipal.FindByIdentity(domainContext, IdentityType.SamAccountName, userName))
        {
            exists = true;
        }
    }
   return exists;
}

Source: Check UserID exists in Active Directory using C#