Advertisement
zefie

escalate to admin when needed .NET

Jun 6th, 2017
479
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.24 KB | None | 0 0
  1.        private static bool checkAdministrator(String args)
  2.         {
  3.             WindowsIdentity identity = WindowsIdentity.GetCurrent();
  4.             WindowsPrincipal principal = new WindowsPrincipal(identity);
  5.             var isAdmin = principal.IsInRole(WindowsBuiltInRole.Administrator);
  6.             if (isAdmin == false)
  7.             {
  8.                 try
  9.                 {
  10.                     var exeName = System.Diagnostics.Process.GetCurrentProcess().MainModule.FileName;
  11.                     ProcessStartInfo startInfo = new ProcessStartInfo(exeName);
  12.                     startInfo.Arguments = args;
  13.                     startInfo.Verb = "runas";
  14.                     System.Diagnostics.Process.Start(startInfo);
  15.                     Application.Exit();
  16.                 }
  17.                 catch
  18.                 {
  19.                     DialogResult errormsg = MessageBox.Show("There was an error gaining administrative privileges", "Error", MessageBoxButtons.RetryCancel, MessageBoxIcon.Error);
  20.                     if (errormsg == DialogResult.Retry)
  21.                     {
  22.                         checkAdministrator(args);
  23.                     }
  24.                 }
  25.                 return false;
  26.             }
  27.             return true;
  28.         }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement