Skip to content

Instantly share code, notes, and snippets.

@fredrikhaglund
Created June 20, 2014 23:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save fredrikhaglund/331d16ad1707d614e480 to your computer and use it in GitHub Desktop.
Save fredrikhaglund/331d16ad1707d614e480 to your computer and use it in GitHub Desktop.
Check if a user is an admin and if not try to elevate the application by restarting itself. When using the verb "runas" User Account Control will popup a dialog and ask for permission to include administrative rights or to login as an administrator.
public static string ProcessFilename
{
get { return Process.GetCurrentProcess().MainModule.FileName; }
}
private static bool HasAdministrativeRight()
{
WindowsIdentity windowsIdentity = WindowsIdentity.GetCurrent();
return windowsIdentity != null
&& new WindowsPrincipal(windowsIdentity).IsInRole(WindowsBuiltInRole.Administrator);
}
private static void RestartElevated(string command)
{
var processInfo = new ProcessStartInfo
{
Verb = "runas",
FileName = ProcessFilename,
Arguments = command
};
try
{
Process.Start(processInfo);
}
catch (Win32Exception)
{
//Do nothing. Probably the user canceled the UAC window
}
}
@fredrikhaglund
Copy link
Author

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment