Purely for reasons of my own curiosity, I am attempting to create a console application in c# that will elevate itself if it sees that it is not running as admin.
The code that I have at the moment is as follows:
using System;
using System.Diagnostics;
using System.Reflection;
using System.Security.Principal;
namespace SelfElevator
{
class Program
{
static void Main(string[] args)
{
if (!IsAdmin())
{
ProcessStartInfo proc = new()
{
UseShellExecute = true,
WorkingDirectory = Environment.CurrentDirectory,
FileName = Assembly.GetEntryAssembly().Location,
Verb = "runas"
};
try
{
Process.Start(proc);
}
catch (Exception e)
{
Console.WriteLine(e);
throw;
}
}
}
private static bool IsAdmin()
{
WindowsIdentity id = WindowsIdentity.GetCurrent();
WindowsPrincipal principal = new(id);
return principal.IsInRole(WindowsBuiltInRole.Administrator);
}
}
}
When I attempt to execute this I receive the error "No application is associated with the specified file for this operation."
I have done some googling and have concluded that perhaps this might be connected to the use of the runas
verb. How and why (and what I might do to correct) though is still eluding me. Note that I am explicitly not including an application.manifest
as I want the application to start unprivileged, detect that it is in that state then restart itself elevated. I also do not mind dealing with the appearance of a UAC prompt. I'm not trying to hack systems - I would just like to understand how to accomplish this process.