Sometimes you need to run your application with elevated privileges to get past issues with UAC. If you need to insure that your application is always run with administrator privileges, this little bit of code can help.
Sub Main()
Dim sArgs As String() = System.Environment.GetCommandLineArgs()
If sArgs.Contains("-runasadmin") Then
SomeMethod()
Else
ReDim Preserve sArgs(sArgs.Length + 1)
sArgs(sArgs.Length - 1) = "-runasadmin"
Dim oProcessStartInfo As System.Diagnostics.ProcessStartInfo = _
New ProcessStartInfo( _
Reflection.Assembly.GetEntryAssembly().Location, _
Join(sArgs, " "))
oProcessStartInfo.Verb = "runas"
Dim oProcess As New System.Diagnostics.Process()
With oProcess
.EnableRaisingEvents = True
.StartInfo = oProcessStartInfo
.Start()
.WaitForExit()
End With
End If
End Sub
The first thing we do is to get the command line arguments. Why? This is the easiest way to tell our running application that we want it to do something special.
The next thing to do is determine if we are running elevated or not. If we are, let's go do what we are supposed to be doing. The way I used to determine if we are elevated is to add a command line argument of -runasadmin
. Please be aware that this is not something added by Windows, but manually by my code.
If the code is not running elevated, then let's re-launch the application with administrator privileges. This is accomplished by first adding
-runasadmin
to the existing command line arguments. Create an
System.Diagnostics.ProcessStartInfo
object that will tell our application to request the administrator privileges. Adding the verb
runas
to the
System.Diagnostics.ProcessStartInfo
is what does the magic. Create a new
System.Diagnostics.Process
, add the
System.Diagnostics.ProcessStartInfo
. Start the process. Idle until the child process completes.