I have a console app that deletes some files, and it can only do that if it is started as administrator.
When the app is started not as administrator I would prefer for it to:
(kinda like notepad++ when you try to edit a certain file, it asks you if you want to restart as administrator)
is this something easy to do in C#?
Thanks to the wise advice in the comments, I managed to get it done.
static void Main()
{
if (!IsAdministrator())
{
Console.WriteLine("restarting as admin");
StartAsAdmin(Assembly.GetExecutingAssembly().Location);
return;
}
...
}
public static bool IsAdministrator()
{
var identity = WindowsIdentity.GetCurrent();
var principal = new WindowsPrincipal(identity);
return principal.IsInRole(WindowsBuiltInRole.Administrator);
}
public static void StartAsAdmin(string fileName)
{
var proc = new Process
{
StartInfo =
{
FileName = fileName,
UseShellExecute = true,
Verb = "runas"
}
};
proc.Start();
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.