Проверка прав администратора - C#

Узнай цену своей работы

Формулировка задачи:

Для работы моего приложения нужны права администратора, как проверить с какими правами запустилась программа

Решение задачи: «Проверка прав администратора»

textual
Листинг программы
  1. /// <summary>
  2. /// The function checks whether the primary access token of the process belongs
  3. /// to user account that is a member of the local Administrators group, even if
  4. /// it currently is not elevated.
  5. /// </summary>
  6. /// <returns>
  7. /// Returns true if the primary access token of the process belongs to user
  8. /// account that is a member of the local Administrators group. Returns false
  9. /// if the token does not.
  10. /// </returns>
  11. /// <exception cref="System.ComponentModel.Win32Exception">
  12. /// When any native Windows API call fails, the function throws a Win32Exception
  13. /// with the last error code.
  14. /// </exception>
  15. internal bool IsUserInAdminGroup()
  16. {
  17.     bool fInAdminGroup = false;
  18.     SafeTokenHandle hToken = null;
  19.     SafeTokenHandle hTokenToCheck = null;
  20.     IntPtr pElevationType = IntPtr.Zero;
  21.     IntPtr pLinkedToken = IntPtr.Zero;
  22.     int cbSize = 0;
  23.  
  24.     try
  25.     {
  26.         // Open the access token of the current process for query and duplicate.
  27.         if (!NativeMethod.OpenProcessToken(Process.GetCurrentProcess().Handle,
  28.             NativeMethod.TOKEN_QUERY | NativeMethod.TOKEN_DUPLICATE, out hToken))
  29.         {
  30.             throw new Win32Exception(Marshal.GetLastWin32Error());
  31.         }
  32.  
  33.         // Determine whether system is running Windows Vista or later operating
  34.         // systems (major version >= 6) because they support linked tokens, but
  35.         // previous versions (major version < 6) do not.
  36.         if (Environment.OSVersion.Version.Major >= 6)
  37.         {
  38.             // Running Windows Vista or later (major version >= 6).
  39.             // Determine token type: limited, elevated, or default.
  40.  
  41.             // Allocate a buffer for the elevation type information.
  42.             cbSize = sizeof(TOKEN_ELEVATION_TYPE);
  43.             pElevationType = Marshal.AllocHGlobal(cbSize);
  44.             if (pElevationType == IntPtr.Zero)
  45.             {
  46.                 throw new Win32Exception(Marshal.GetLastWin32Error());
  47.             }
  48.  
  49.             // Retrieve token elevation type information.
  50.             if (!NativeMethod.GetTokenInformation(hToken,
  51.             TOKEN_INFORMATION_CLASS.TokenElevationType, pElevationType,
  52.                 cbSize, out cbSize))
  53.             {
  54.                 throw new Win32Exception(Marshal.GetLastWin32Error());
  55.             }
  56.  
  57.             // Marshal the TOKEN_ELEVATION_TYPE enum from native to .NET.
  58.             TOKEN_ELEVATION_TYPE elevType = (TOKEN_ELEVATION_TYPE)
  59.             Marshal.ReadInt32(pElevationType);
  60.  
  61.             // If limited, get the linked elevated token for further check.
  62.             if (elevType == TOKEN_ELEVATION_TYPE.TokenElevationTypeLimited)
  63.             {
  64.                 // Allocate a buffer for the linked token.
  65.                 cbSize = IntPtr.Size;
  66.                 pLinkedToken = Marshal.AllocHGlobal(cbSize);
  67.                 if (pLinkedToken == IntPtr.Zero)
  68.                 {
  69.                     throw new Win32Exception(Marshal.GetLastWin32Error());
  70.                 }
  71.  
  72.                 // Get the linked token.
  73.                 if (!NativeMethod.GetTokenInformation(hToken,
  74.                 TOKEN_INFORMATION_CLASS.TokenLinkedToken, pLinkedToken,
  75.                     cbSize, out cbSize))
  76.                 {
  77.                     throw new Win32Exception(Marshal.GetLastWin32Error());
  78.                 }
  79.  
  80.                 // Marshal the linked token value from native to .NET.
  81.                 IntPtr hLinkedToken = Marshal.ReadIntPtr(pLinkedToken);
  82.                 hTokenToCheck = new SafeTokenHandle(hLinkedToken);
  83.             }
  84.         }
  85.                
  86.         // CheckTokenMembership requires an impersonation token. If we just got
  87.         // a linked token, it already is an impersonation token.  If we did not
  88.         // get a linked token, duplicate the original into an impersonation
  89.         // token for CheckTokenMembership.
  90.         if (hTokenToCheck == null)
  91.         {
  92.             if (!NativeMethod.DuplicateToken(hToken,
  93.                 SECURITY_IMPERSONATION_LEVEL.SecurityIdentification,
  94.                 out hTokenToCheck))
  95.             {
  96.                 throw new Win32Exception(Marshal.GetLastWin32Error());
  97.             }
  98.         }
  99.  
  100.         // Check if the token to be checked contains admin SID.
  101.         WindowsIdentity id = new WindowsIdentity(hTokenToCheck.DangerousGetHandle());
  102.         WindowsPrincipal principal = new WindowsPrincipal(id);
  103.         fInAdminGroup = principal.IsInRole(WindowsBuiltInRole.Administrator);
  104.     }
  105.     finally
  106.     {
  107.         // Centralized cleanup for all allocated resources.
  108.         if (hToken != null)
  109.         {
  110.             hToken.Close();
  111.             hToken = null;
  112.         }
  113.         if (hTokenToCheck != null)
  114.         {
  115.             hTokenToCheck.Close();
  116.             hTokenToCheck = null;
  117.         }
  118.         if (pElevationType != IntPtr.Zero)
  119.         {
  120.             Marshal.FreeHGlobal(pElevationType);
  121.             pElevationType = IntPtr.Zero;
  122.         }
  123.         if (pLinkedToken != IntPtr.Zero)
  124.         {
  125.             Marshal.FreeHGlobal(pLinkedToken);
  126.             pLinkedToken = IntPtr.Zero;
  127.         }
  128.     }
  129.     return fInAdminGroup;
  130. }

ИИ поможет Вам:


  • решить любую задачу по программированию
  • объяснить код
  • расставить комментарии в коде
  • и т.д
Попробуйте бесплатно

Оцени полезность:

5   голосов , оценка 3.6 из 5

Нужна аналогичная работа?

Оформи быстрый заказ и узнай стоимость

Бесплатно
Оформите заказ и авторы начнут откликаться уже через 10 минут
Похожие ответы