How to check current user role is admin


On windows many time we need to check current user role. In C# it is very easy and one can do this by just using function below. This is done by using three dot net classes WindowsIdentity, WindowsPrincipal and WindowsBuiltInRole. This function can be used in any dotnet c# application.

        public static bool IsUserAdmin()
        {
            bool isAdmin = false;
            try
            {
                //Get cuurent user identity
                WindowsIdentity user = WindowsIdentity.GetCurrent();
                WindowsPrincipal principal = new WindowsPrincipal(user);
                //Check if user role is built in admin role
                isAdmin = principal.IsInRole(WindowsBuiltInRole.Administrator);
            }
            catch (UnauthorizedAccessException ex)
            {
                isAdmin = false;
            }
            catch (Exception ex)
            {
                isAdmin = false;
            }
            return isAdmin;
        }
    }