PermissionTool.cs 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. //############################################################
  2. // https://github.com/yuzhengyang
  3. // author:yuzhengyang
  4. //############################################################
  5. using Azylee.Core.WindowsUtils.APIUtils;
  6. using System;
  7. using System.Security.Principal;
  8. namespace Azylee.Core.AppUtils
  9. {
  10. public class PermissionTool
  11. {
  12. /// <summary>
  13. /// 当前登录用户是否为管理员
  14. /// 百万次执行时间:26947、28705、28244 ms
  15. /// </summary>
  16. /// <returns></returns>
  17. [Obsolete]
  18. public static bool IsAdministrator()
  19. {
  20. WindowsIdentity identity = WindowsIdentity.GetCurrent();
  21. WindowsPrincipal principal = new WindowsPrincipal(identity);
  22. return principal.IsInRole(WindowsBuiltInRole.Administrator);
  23. }
  24. /// <summary>
  25. /// 当前登录用户是否为管理员
  26. /// 百万次执行时间:8063、9097、9755 ms
  27. /// </summary>
  28. /// <returns></returns>
  29. public static bool IsAdmin()
  30. {
  31. const int SECURITY_BUILTIN_DOMAIN_RID = 0x20;
  32. const int DOMAIN_ALIAS_RID_ADMINS = 0x220;
  33. byte[] NtAuthority = new byte[6];
  34. NtAuthority[5] = 5; // SECURITY_NT_AUTHORITY
  35. IntPtr AdministratorsGroup;
  36. int ret = PermissionAPI.AllocateAndInitializeSid(NtAuthority, 2, SECURITY_BUILTIN_DOMAIN_RID, DOMAIN_ALIAS_RID_ADMINS, 0, 0, 0, 0, 0, 0, out AdministratorsGroup);
  37. if (ret != 0)
  38. {
  39. if (PermissionAPI.CheckTokenMembership(IntPtr.Zero, AdministratorsGroup, ref ret) == 0)
  40. {
  41. ret = 0;
  42. }
  43. PermissionAPI.FreeSid(AdministratorsGroup);
  44. }
  45. return (ret != 0);
  46. }
  47. }
  48. }