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.
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 ?
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.Administrator) Then ...
Just change the app.manifest to force require administration:
Solution Explorer --> My Project --> View Windows Settings
<requestedExecutionLevel level="requireAdministrator" uiAccess="false" />
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
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.
© 2022 - 2024 — McMap. All rights reserved.