My application is running as an administrator (elevated), but I need to run certain blocks of code in the current user's context (unelevated).
How can I run a given block of code in an unelevated context?
Is there a way to do this with impersonation, that doesn't require me to know the user's domain, name, and password?
Is there another API for this, or a way to do it simply with attributes?
Likewise, is there a way to detect that I'm currently running in an elevated context, so that I know I need to de-elevate in the first place?
I'm using C# 6.0, .NET 4.x (where x >= 5), and Visual Studio 2015.
To check if you're in elevated context:
static bool IsAdministrator()
{
WindowsIdentity identity = WindowsIdentity.GetCurrent();
WindowsPrincipal principal = new WindowsPrincipal(identity);
return principal.IsInRole (WindowsBuiltInRole.Administrator);
}
(Taken from: Detect if running as Administrator with or without elevated privileges?)