Is there a canonical way to test to see if the process has administrative privileges on a machine?
I\'m going to be starting a long running process, and much later
Use can use WMI with something like this to find out if the account is an admin, and just about anything else you want to know about there account
using System;
using System.Management;
using System.Windows.Forms;
namespace WMISample
{
public class MyWMIQuery
{
public static void Main()
{
try
{
ManagementObjectSearcher searcher =
new ManagementObjectSearcher("root\\CIMV2",
"SELECT * FROM Win32_UserAccount");
foreach (ManagementObject queryObj in searcher.Get())
{
Console.WriteLine("-----------------------------------");
Console.WriteLine("Win32_UserAccount instance");
Console.WriteLine("-----------------------------------");
Console.WriteLine("AccountType: {0}", queryObj["AccountType"]);
Console.WriteLine("FullName: {0}", queryObj["FullName"]);
Console.WriteLine("Name: {0}", queryObj["Name"]);
}
}
catch (ManagementException e)
{
MessageBox.Show("An error occurred while querying for WMI data: " + e.Message);
}
}
}
}
To make it easier to get started download WMI Creator
you can also use this it access active directory (LDAP) or anything else on you computer/network
This will check if user is in the local Administrators group (assuming you're not checking for domain admin permissions)
using System.Security.Principal;
public bool IsUserAdministrator()
{
//bool value to hold our return value
bool isAdmin;
WindowsIdentity user = null;
try
{
//get the currently logged in user
user = WindowsIdentity.GetCurrent();
WindowsPrincipal principal = new WindowsPrincipal(user);
isAdmin = principal.IsInRole(WindowsBuiltInRole.Administrator);
}
catch (UnauthorizedAccessException ex)
{
isAdmin = false;
}
catch (Exception ex)
{
isAdmin = false;
}
finally
{
if (user != null)
user.Dispose();
}
return isAdmin;
}
If you want to make sure your solution works in Vista UAC, and have .Net Framework 3.5 or better, you might want to use the System.DirectoryServices.AccountManagement namespace. Your code would look something like:
bool isAllowed = false;
using (PrincipalContext pc = new PrincipalContext(ContextType.Machine, null))
{
UserPrincipal up = UserPrincipal.Current;
GroupPrincipal gp = GroupPrincipal.FindByIdentity(pc, "Administrators");
if (up.IsMemberOf(gp))
isAllowed = true;
}
What about:
using System.Runtime.InteropServices;
internal static class Useful {
[DllImport("shell32.dll", EntryPoint = "IsUserAnAdmin")]
public static extern bool IsUserAnAdministrator();
}