且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

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

更新时间:2023-12-03 23:05:28

 公共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#