PermissionTool.cs 1.9 KB

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