Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if user is a Domain User or Local User [duplicate]

Tags:

c#

.net

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

like image 531
Sam Stephenson Avatar asked Oct 03 '12 14:10

Sam Stephenson


4 Answers

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#

like image 116
Micah Armantrout Avatar answered Oct 16 '22 14:10

Micah Armantrout


For me this has worked quite well so far. (left usings away).

bool IsLocalUser(string accountName)
{
  var domainContext = new PrincipalContext(ContextType.Machine);
  return Principal.FindByIdentity(domainContext, accountName) != null;
}

But be aware that this will not recognize the "System" account. We check that separately because it's always a local account.

like image 39
Lynx Envoy Avatar answered Oct 16 '22 13:10

Lynx Envoy


David is on the money, to check if the current user is part of the domain, you can check the Environment.UserDomainName and compare this with the current user.

Bit more info at MSDN

like image 36
leon.io Avatar answered Oct 16 '22 13:10

leon.io


A local user will have the account name prefixed with the machine name. A domain user's account name will be prefixed with its originating domain. If the machine name and the account prefix name don't match, or if the account name prefix matches the local machine, it's generally safe to assume its a local account.

like image 45
David W Avatar answered Oct 16 '22 13:10

David W