r/visualbasic • • Dec 30 '20

Tips & Tricks Checking if current process is being run with Administrative rights

I just got caught by an issue i knew about, and warned myself about in my own readme! I thought i would share.

When using SSL via HttpClientHandler.ClientCertificates without Administrative rights, HttpClient's GetAsync() and PostAsync() fails with two errors:

(1/2) HttpRequestException: The SSL connection could not be established, see inner exception.
(2/2) Win32Exception: The credentials supplied to the package were not recognized

Wonderfully descriptive...Anyway, after converting my application from Framework to .Net 5, i forgot about this, and ran my app as a regular user (via vs). Part of it worked fine, part of it failed. Wondering what i did wrong, i finally remembered i needed to be Administrator.

Great! It works. But how do i stop myself from making the same mistake in the future? Well, obviously i ought to check if the current user/process is running as administrator. A quick search found some sample code, which i converted to VB, and then realized most of the lines were redundant. So, i ended up using:

Imports System.Security.Principal

If Not New WindowsPrincipal(WindowsIdentity.GetCurrent()).IsInRole(WindowsBuiltInRole.Administrator) Then

6 Upvotes

0 comments sorted by