AdminRelauncher.cs 1.1 KB

12345678910111213141516171819202122232425262728293031323334353637
  1. using System;
  2. using System.Diagnostics;
  3. using System.Reflection;
  4. using System.Security.Principal;
  5. public static class AdminRelauncher
  6. {
  7. public static void RelaunchIfNotAdmin()
  8. {
  9. if (!Debugger.IsAttached && !RunningAsAdmin())
  10. {
  11. Console.WriteLine("Running as admin required!");
  12. ProcessStartInfo proc = new ProcessStartInfo();
  13. proc.UseShellExecute = true;
  14. proc.WorkingDirectory = Environment.CurrentDirectory;
  15. proc.FileName = Assembly.GetEntryAssembly().CodeBase;
  16. proc.Verb = "runas";
  17. try
  18. {
  19. Process.Start(proc);
  20. }
  21. catch (Exception ex)
  22. {
  23. Console.WriteLine("This program must be run as an administrator! \n\n" + ex.ToString());
  24. }
  25. Environment.Exit(0);
  26. }
  27. }
  28. private static bool RunningAsAdmin()
  29. {
  30. WindowsIdentity id = WindowsIdentity.GetCurrent();
  31. WindowsPrincipal principal = new WindowsPrincipal(id);
  32. return principal.IsInRole(WindowsBuiltInRole.Administrator);
  33. }
  34. }