C # Check whether the job runs as an administrator,

Source: Internet
Author: User

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.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.