Search
 
SCRIPT & CODE EXAMPLE
 
CODE EXAMPLE FOR CSHARP

c#: how to request for admin priviledge

/*
A more standard approach (but obsolete) to demand in code that the current user has Admin privileges
before running one or more guarded code is to use the PrincipalPermissionAttribute
for the guarded method of your program.

The following is an example :
*/

// NOTE PrincipalPermissionAttribute.PrincipalPermissionAttribute(SecurityAction) is obsolete
[PrincipalPermissionAttribute(SecurityAction.Demand, Role = @"BUILTINAdministrators")]
private static void AdministratorsCode()
{
  Console.WriteLine("Administrators Only");
}

/*
Declare a usage of the System.Security.Principal and System.Security.Permissions namespaces.
Early in your program, before calling a method like AdministratorsCode(), you need to call :
*/

System.AppDomain.CurrentDomain.SetPrincipalPolicy(PrincipalPolicy.WindowsPrincipal);

/*
Below is a complete example code :
*/

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Security.Principal;
using System.Security.Permissions;

namespace ConsoleProgramRunAsAdmon
{
    class Program
    {
        [PrincipalPermissionAttribute(SecurityAction.Demand, Role = @"BUILTINAdministrators")]
        private static void AdministratorsCode()
        {
            Console.WriteLine("Administrators Only");
        }

        static void Main(string[] args)
        {
            try
            {
                System.AppDomain.CurrentDomain.SetPrincipalPolicy(PrincipalPolicy.WindowsPrincipal);
                AdministratorsCode();
            }
            catch(Exception ex)
            {
                Console.WriteLine("An exception occurred : " + ex.Message);
            }

            Console.ReadKey();
        }
    }
}

// Hope that helps
Source by social.msdn.microsoft.com #
 
PREVIOUS NEXT
Tagged: #request #admin #priviledge
ADD COMMENT
Topic
Name
3+8 =