zefie icon

escalate to admin when needed .NET

zefie | PRO | 06/06/17 11:09:14 AM UTC | 0 ⭐ | 830 👁️ | Never ⏰ | []
C# |

1.24 KB

|

None

|

0 👍

/

0 👎

       private static bool checkAdministrator(String args)
        {
            WindowsIdentity identity = WindowsIdentity.GetCurrent();
            WindowsPrincipal principal = new WindowsPrincipal(identity);
            var isAdmin = principal.IsInRole(WindowsBuiltInRole.Administrator);
            if (isAdmin == false)
            {
                try
                {
                    var exeName = System.Diagnostics.Process.GetCurrentProcess().MainModule.FileName;
                    ProcessStartInfo startInfo = new ProcessStartInfo(exeName);
                    startInfo.Arguments = args;
                    startInfo.Verb = "runas";
                    System.Diagnostics.Process.Start(startInfo);
                    Application.Exit();
                }
                catch
                {
                    DialogResult errormsg = MessageBox.Show("There was an error gaining administrative privileges", "Error", MessageBoxButtons.RetryCancel, MessageBoxIcon.Error);
                    if (errormsg == DialogResult.Retry)
                    {
                        checkAdministrator(args);
                    }
                }
                return false;
            }
            return true;
        }

Comments