Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

Elevate your application at start up

0.00/5 (No votes)
26 Feb 2013 2  
Sometimes you need to run your application with elevated privileges to get past issues with UAC.  

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
    ' Running with elevated privileges
    SomeMethod()
  Else
    ' Re-launch the current application with elevated privileges
    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
      ' Enable the WaitForExit method
      .EnableRaisingEvents = True
      .StartInfo = oProcessStartInfo

      ' Start the process.
      .Start()

      ' Sleep until the process has completed.
      .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.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here