relaunching as an admin

In library-load-dbg-flags the code I posted requires one to run it as as admin. Now how do you detect that you need to run as an admin from code is the question i was pondering about.

With C# it is quite easy to detect whether you have admin priviledges or not:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
private bool IsRunAsAdmin()
{
    try
    {
        WindowsIdentity id = WindowsIdentity.GetCurrent();
        WindowsPrincipal principal = new WindowsPrincipal(id);
        return principal.IsInRole(WindowsBuiltInRole.Administrator);
    }
    catch (Exception)
    {
        return false;
    }
}


Now, the question is about relaunching on detecting. Following code should do it:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
//  https://stackoverflow.com/a/46080075/916549
private void AdminRelauncher()
{
    if (!IsRunAsAdmin())
    {
        ProcessStartInfo proc = new ProcessStartInfo();
        proc.UseShellExecute = true;
        proc.WorkingDirectory = Environment.CurrentDirectory;
        proc.FileName = Assembly.GetEntryAssembly().CodeBase;

        proc.Verb = "runas";

        try
        {
            Process.Start(proc);
            Application.Current.Shutdown(0);
        }
        catch (Exception ex)
        {
            MessageBox.Show("This program must be run as an administrator! \n\n" + ex.ToString());
        }
    }
    else
    {
        SetupFlags = true;
    }
}


With above functions and code from last post, one can easily roll out an utility that can set/reset GlobalFlag for library load snaps debugging..