PermissionTool.cs 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940
  1. //############################################################
  2. // https://github.com/yuzhengyang
  3. // author:yuzhengyang
  4. //############################################################
  5. using System;
  6. using System.Security.Principal;
  7. using Y.Utils.WindowsUtils.APIUtils;
  8. namespace Y.Utils.AppUtils
  9. {
  10. public class PermissionTool
  11. {
  12. public static bool IsAdministrator()
  13. {
  14. WindowsIdentity identity = WindowsIdentity.GetCurrent();
  15. WindowsPrincipal principal = new WindowsPrincipal(identity);
  16. return principal.IsInRole(WindowsBuiltInRole.Administrator);
  17. }
  18. public static bool IsAdmin()
  19. {
  20. const int SECURITY_BUILTIN_DOMAIN_RID = 0x20;
  21. const int DOMAIN_ALIAS_RID_ADMINS = 0x220;
  22. byte[] NtAuthority = new byte[6];
  23. NtAuthority[5] = 5; // SECURITY_NT_AUTHORITY
  24. IntPtr AdministratorsGroup;
  25. int ret = PermissionAPI.AllocateAndInitializeSid(NtAuthority, 2, SECURITY_BUILTIN_DOMAIN_RID, DOMAIN_ALIAS_RID_ADMINS, 0, 0, 0, 0, 0, 0, out AdministratorsGroup);
  26. if (ret != 0)
  27. {
  28. if (PermissionAPI.CheckTokenMembership(IntPtr.Zero, AdministratorsGroup, ref ret) == 0)
  29. {
  30. ret = 0;
  31. }
  32. PermissionAPI.FreeSid(AdministratorsGroup);
  33. }
  34. return (ret != 0);
  35. }
  36. }
  37. }