public static void GrantTokenPrivilege(string privilege) { OpenProcessToken(GetCurrentProcess(), TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, out IntPtr tokenHandle); SingleTokenPrivilege tokenPrivilege = new SingleTokenPrivilege { Count = 1, Luid = 0, Attributes = SE_PRIVILEGE_ENABLED }; LookupPrivilegeValue(null, privilege, out tokenPrivilege.Luid); bool successful = AdjustTokenPrivileges(tokenHandle, false, ref tokenPrivilege, 0, IntPtr.Zero, IntPtr.Zero); if (!successful) { throw new SecurityException($"Can't grant token privilege {privilege}"); } }
private static extern bool AdjustTokenPrivileges(IntPtr tokenHandle, bool disableAllPrivileges, ref SingleTokenPrivilege newState, int bufferLength, IntPtr previousState, IntPtr returnLength);