Obtain Elevated Privileges - CSharp System

CSharp examples for System:Windows

Description

Obtain Elevated Privileges

Demo Code


using System;/*from www .  j  ava2  s .c o m*/
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();
        }
    }

Result


Related Tutorials