CSharp examples for Operating System:Windows
Obtain Elevated Privileges
using System;//from www . ja v a 2 s . c om using System.Collections.Generic; using System.Linq; using System.Text; using System.Security.Principal; using System.Diagnostics; class Program { static void Main(string[] args) { // check to see if the first argument is "elevated" if (args.Length > 0 && args[0] == "elevated") { Console.WriteLine("Started with command line argument"); performElevatedTasks(); } else { Console.WriteLine("Started without command line argument"); performNormalTasks(); } } static void performNormalTasks() { if (checkElevatedPrivilege()) { performElevatedTasks(); } else { startElevatedInstance(); } } static void performElevatedTasks() { if (checkElevatedPrivilege()) { Console.WriteLine("Elevated tasks performed"); } else { Console.WriteLine("Cannot perform elevated tasks"); } } static bool checkElevatedPrivilege() { WindowsIdentity winIdentity = WindowsIdentity.GetCurrent(); WindowsPrincipal winPrincipal = new WindowsPrincipal(winIdentity); return winPrincipal.IsInRole (WindowsBuiltInRole.Administrator); } static void startElevatedInstance() { ProcessStartInfo procstartinf = new ProcessStartInfo("Recipe14-15.exe"); procstartinf.Arguments = "elevated"; procstartinf.Verb = "runas"; Process.Start(procstartinf).WaitForExit(); } }