0

Can someone help me with this code, at the line concerning the condition if I'm and Administrator it returns false despite logged in as Administrator.

The C# Code:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Security.Principal;


namespace WinFormsAppDummies
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            // Added code from the book C# 5.0 Dummies
            WindowsIdentity myIdentity = WindowsIdentity.GetCurrent();
            WindowsPrincipal myPrincipal = new WindowsPrincipal(myIdentity);
            if (myPrincipal.IsInRole("Accounting"))
            {
                AccountingButton.Visible = true;
            }
            else if(myPrincipal.IsInRole("Sales"))
            {
                SalesButton.Visible = true;
            }
            else if (myPrincipal.IsInRole("Management"))
            {
                ManagerButton.Visible = true;
            }
            else if (myPrincipal.IsInRole(WindowsBuiltInRole.Administrator)) // <--- RETURNS FALSE!
            {
                ManagerButton.Visible = true;
            }
        }

        private void SalesButton_Click(object sender, EventArgs e)
        {

        }

        private void AccountingButton_Click(object sender, EventArgs e)
        {

        }

        private void ManagerButton_Click(object sender, EventArgs e)
        {

        }
    }
}

Can someone help me adjusting the previous code so that the Rule is seen as Administrator?

Rui Monteiro
  • 181
  • 1
  • 7
  • What's the UAC/Elevation situation here? E.g. are you able to right-click the application and choose a "Run as Administrator" option and if so, do you get a different answer? – Damien_The_Unbeliever Sep 15 '21 at 06:39
  • Ok, you solve it, I run it from the compiler, now I run it as Administrator and it worked. Thanks :) – Rui Monteiro Sep 15 '21 at 09:08

0 Answers0