C # Check if current login user is Admin user (remote machine)
I know there are several discussions on this, but no one answers my exact question. I am looking for a method that will check Remotely if the current user with user rights has administrator rights. Whether he is a member of the machine's local built-in Administrators group, or a member of a nested group within Administrators, such as Domain Admins. I found several methods, but each only provides half of the solution.
Method # 1 (work remotely, but only checks the local Administrators group):
private bool isAdmin()
{
ArrayList mem2 = new ArrayList();
string hostName = basicinfomodel.Loggedusername; //a username I get from another class
try
{
using (DirectoryEntry machine = new DirectoryEntry("WinNT://" + mycomputer.myComputerName)) // remote computer that I get from another class
{
//get local admin group
using (DirectoryEntry group = machine.Children.Find("Administrators", "Group"))
{
//get all members of local admin group
object members = group.Invoke("Members", null);
foreach (object member in (IEnumerable)members)
{
//get account name
string accountName = new DirectoryEntry(member).Name;
mem2.Add(new DirectoryEntry(member).Name);
}
}
}
}
catch (Exception ex)
{
// catch
}
if (mem2.Contains(hostName.ToUpper()) || mem2.Contains(hostName.ToLower()))
return true;
else
return false;
}
Method # 2 (check both local and domain admin rights, but don't work remotely)
static bool isAdmin()
{
WindowsIdentity User = new WindowsIdentity(@"user01");
WindowsPrincipal princ = new WindowsPrincipal(User);
return princ.IsInRole(WindowsBuiltInRole.Administrator);
}
as I said, I haven't found any method that meets both needs.
- check if the user really has administrator rights.
- do it remotely
thanks for the help!
source to share
Well I think I found a way to do it, I am sharing that other people will want to use it. I played with several methods I found and created the following (seems to work)
static bool isAdmin(string username, string machinename)
{
using (PrincipalContext ctxMacine = new PrincipalContext(ContextType.Machine, machinename))
{
using (PrincipalContext ctxDomain = new PrincipalContext(ContextType.Domain))
{
UserPrincipal up = UserPrincipal.FindByIdentity(ctxDomain, IdentityType.SamAccountName, username);
GroupPrincipal gp = GroupPrincipal.FindByIdentity(ctxMacine, "Administrators");
foreach (UserPrincipal usr in gp.GetMembers(true))
{
if (up != null)
{
if (up.SamAccountName.ToUpper() == usr.SamAccountName.ToUpper())
{
return true;
}
}
}
}
}
return false;
}
source to share