Run as administrator

Costas

Administrator
Staff member
JavaScript:
//check if admin, if not run as admin :
WindowsIdentity windowsIdentity = WindowsIdentity.GetCurrent();
WindowsPrincipal windowsPrincipal = new WindowsPrincipal(windowsIdentity);
if (!windowsPrincipal.IsInRole(WindowsBuiltInRole.Administrator))
{
    if (MessageBox.Show(Resource1.adminQuestion, Text, MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
    {
        ProcessStartInfo startInfo = new ProcessStartInfo();
        startInfo.UseShellExecute = true;
        startInfo.WorkingDirectory = Environment.CurrentDirectory;
        startInfo.FileName = Application.ExecutablePath;
        startInfo.Verb = "runas";
        Process.Start(startInfo);
        this.Close();
        Application.Exit();
    }
}
 
 
Start a 3rd app as admin
https://stackoverflow.com/questions/2532769/how-to-start-a-process-as-administrator-mode-in-c-sharp
 

 
Manifest use
https://stackoverflow.com/questions/2818179/how-do-i-force-my-net-application-to-run-as-administrator
 

yPBnEWs.jpg


add the manifest file to your PRJ. when build embedded to exe, no need to copy near exe. valid manifest to require admin rights on run is :
JavaScript:
//src - https://victorhurdugaci.com/using-uac-with-c-part-2
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<assembly xmlns="urn:schemas-microsoft-com:asm.v1" manifestVersion="1.0">
   <assemblyIdentity version="1.0.0.0" processorArchitecture="X86" name="UACApp" type="win32"/>
   [TR]
      <security>
         <requestedPrivileges>
            <requestedExecutionLevel level="requireAdministrator"/>
         </requestedPrivileges>
      </security>
   </trustInfo>
</assembly>
 
if for any reason when you starting the exe, an error appears, you can view the debug at :
See MyComputer > rclick > Manage > Event Viewer > Windows Logs > Application
 
the levels explained :
lq6vku2.png
 
Top