These are the steps I am doing:
-
Take VS2022 and open it with elevated privileges (as administrator).
-
create a C#/Winform project for .net-8.0
-
Embed a manifest that states:
-
since I want it to always run as administrator in main form i am runing this method, add a script that allows me to relaunch the application as administrator:
private static bool IsRunAsAdmin() { try { WindowsIdentity id = WindowsIdentity.GetCurrent(); WindowsPrincipal principal = new(id); return principal.IsInRole(WindowsBuiltInRole.Administrator); } catch (Exception) { return false; } } private static void AdminRelauncher() { if (!IsRunAsAdmin()) { #pragma warning disable CS8602 // Dereference of a possibly null reference. ProcessStartInfo proc = new() { UseShellExecute = true, WorkingDirectory = Environment.CurrentDirectory, FileName = Assembly.GetEntryAssembly().Location.Replace(".dll", ".exe"), Verb = "runas" }; #pragma warning restore CS8602 // Dereference of a possibly null reference. try { Process.Start(proc); Environment.Exit(0); } catch (Exception ex) { Console.WriteLine("This program must be run as an administrator! \n\n" + ex.ToString()); } } }
note: this is not relevant if I am running the VS2022 (IDE) as Administrator, the execution in debug execute the application as administrator (inheriting elevated privileges), the debug is not interrupted, but it does allow me if the executable is opened from the ".exe" lose/relaunch with elevated privileges.
Yes or If the application is run with elevated privileges...
- I have tried running this command in PowerShell opened as administrator:
powershell -Command "Set-ExecutionPolicy -Scope Process -ExecutionPolicy Unrestricted -Force ; (New-Object Security.Principal.WindowsPrincipal([Security.Principal.WindowsIdentity]::GetCurrent())).IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)"
the output is TRUE.
If I invoke this same thing from the application with UseShellExecute = false, I also get TRUE... According to the documentation or what the community claims it should silently ignore Verb and return False.