Created
June 20, 2014 23:22
-
-
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Part of my blog post How to open a link in another browser.