Find IsAdministrator, Build Path in C# WIN Forms


While working with windows application, there might be some scenarios where we required to find whether user is administrator or not and Build Path of the application. In this article we discuss about how to find the user role and build path of the application.

First we will check whether user is administrator or not. Open Microsoft Visual Studio 2013 => create new windows application and write below code.

using System;

using System.Security.Principal;

using System.Windows.Forms;

 

namespace WindowsFormsApplication1

{

    public partial class Form1 : Form

    {

        public Form1()

        {

            InitializeComponent();

        }

 

        private void Form1_Load(object sender, EventArgs e)

        {

            bool isAdmin;

            try

            {

                WindowsIdentity user = WindowsIdentity.GetCurrent();

                WindowsPrincipal principal = new WindowsPrincipal(user);

                isAdmin = principal.IsInRole(WindowsBuiltInRole.Administrator);

            }

            catch (UnauthorizedAccessException ex)

            {

                isAdmin = false;

            }

            catch (Exception ex)

            {

                isAdmin = false;

            }

            MessageBox.Show(isAdmin.ToString());

        }

    }

}

 

As shown above, first we find the login user by using WIndowsIdentity and get the user role by using WindowsPrincipal class.

To find the build path, use the below code.

using System;

using System.IO;

using System.Windows.Forms;

 

namespace WindowsFormsApplication1

{

    public partial class Form1 : Form

    {

        public Form1()

        {

            InitializeComponent();

        }

 

        private void Form1_Load(object sender, EventArgs e)

        {          

            string netVer = System.Reflection.Assembly.GetExecutingAssembly().ImageRuntimeVersion;

            MessageBox.Show(Path.Combine(System.Runtime.InteropServices.RuntimeEnvironment.GetRuntimeDirectory(), "aspnet_compiler.exe"));

        }

    }

}

 

Here we are find the build path by using GetExecutingAssembly() method of Assembly class which is available in System.Reflection namespace.