6

I have made an application and some of its features only work with admin rights,

How can I check if application is running with admin rights or not ?

  • And show a message box if application is not running with admin rights to run as administrator.
Ali Ahmad
  • 81
  • 2
  • 9

4 Answers4

15
Imports System.Security.Principal

Dim identity = WindowsIdentity.GetCurrent()
Dim principal = new WindowsPrincipal(identity)
Dim isElevated as Boolean = principal.IsInRole(WindowsBuiltInRole.Administrator) 
If isElevated Then
  MessageBox.Show("Is Admin")
End If

In VB.Net there is even a shortcut for this:

If My.User.IsInRole(ApplicationServices.BuiltInRole.Administrat‌​or) Then ... 
Ron DeFulio
  • 125
  • 1
  • 7
Abel Masila
  • 736
  • 2
  • 7
  • 25
  • This should be the accepted answer. It answers the OP's question, and I tested the solution and it works perfectly. – Ron DeFulio Oct 21 '18 at 22:14
  • Something is wrong in Windows 10 with this code, all the users are reported like administrators, even Guests without Administrator role – Fidel Orozco Dec 05 '19 at 03:04
3

Just change the app.manifest to force require administration:

Solution Explorer --> My Project --> View Windows Settings

<requestedExecutionLevel level="requireAdministrator" uiAccess="false" />

Mederic
  • 1,949
  • 4
  • 19
  • 36
0

You can try and create a file on the system drive inside a try/catch block, and if it catches an access denied exception, then that means that the app is not running as administrator.

Imports System.IO
Public Class Form1

    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
        Try
            File.Create("c://test.txt")
            MessageBox.Show("Is Admin")
            File.Delete("c://test.txt")
        Catch ex As Exception
            If ex.ToString.Contains("denied") Then
                MessageBox.Show("Is Not Admin")
            End If
        End Try
    End Sub
End Class
Mousa Alfhaily
  • 1,260
  • 3
  • 20
  • 38
0

A version for C# 6 (or later), adapted from the Visual Basic solution posted elsewhere on this page. In the interest of general-purpose use1, here I conceive a bool-valued static property:

(using System.Security.Principal;)

public static bool IsAdministrator =>
    new WindowsPrincipal(WindowsIdentity.GetCurrent())
            .IsInRole(WindowsBuiltInRole.Administrator);


Now having shown this, one must acknowledge that @Mederic's approach does indeed seem superior, since it's unclear precisely what an app might helpfully do after presumably detecting—and reporting—that such a (presumably) critical precondition has failed. Surely it's wiser—and safer—to delegate concerns of this nature to the OS.



1 That is, eliding the "MessageBox" desiderata articulated by the OP.

Glenn Slayden
  • 17,543
  • 3
  • 114
  • 108