C # Check whether the job runs as an administrator,
In some cases, we need to use the administrator privilege to do some things, such as operating the registry, reading and writing files, elevation of permissions, or using the anonymous pipeline to run the net to modify the user password to extract information and configure the system/software. Below I will list several check whether the code runs as an administrator. 1. declare BOOL IsNTAdmin (_ int32 dwReserved, _ int32 lpdwReserved); [DllImport ("advpack. dll", SetLastError = false)]
[Return: financialas (UnmanagedType. Bool)]
Public static extern bool IsNTAdmin (int dwReserved, int lpdwReserved );
Sample Console. WriteLine ("Run as administrator:" + IsNTAdmin (0, 0); 2. declare BOOL IsUserAnAdmin (VOID );
[DllImport ("shell32.dll", SetLastError = false)]
[Return: financialas (UnmanagedType. Bool)]
Public static extern bool IsUserAnAdmin ();
Sample Console. writeLine ("Run as administrator:" + IsUserAnAdmin (); 3. declare using System. security. principal; sample using (WindowsIdentity wi = WindowsIdentity. getCurrent () // user
{
WindowsPrincipal wp = new WindowsPrincipal (wi); // User Group
If (wp. IsInRole (WindowsBuiltInRole. Administrator) // whether the user belongs to the Administrator
Console. WriteLine ("Run as administrator: true ");
Else
Console. WriteLine ("Run as administrator: false ");
} Among the three methods listed above, it is best to use method 1 and method 2. Method 3 will consume more memory, and the focus is that its speed is indeed different from the first two methods. not big, but people who use high-precision timers should be able to test them.
Zookeeper
Copyright Disclaimer: This article is an original article by the blogger and cannot be reproduced without the permission of the blogger.