/// <summary> /// Tries to enable the specified privilege. /// </summary> /// <param name="privilege">The privilege to enable.</param> /// <exception cref="PrivilegeException">There was an error while requesting a required privilege.</exception> /// <remarks>Thanks to Michael S. Muegel for notifying us about a bug in this code.</remarks> protected static void EnableToken(string privilege) { if (!CheckEntryPoint("advapi32.dll", "AdjustTokenPrivileges")) { return; } IntPtr tokenHandle = IntPtr.Zero; LUID privilegeLUID = new LUID(); TOKEN_PRIVILEGES newPrivileges = new TOKEN_PRIVILEGES(); TOKEN_PRIVILEGES tokenPrivileges; if ( OpenProcessToken(Process.GetCurrentProcess().Handle, TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, ref tokenHandle) == 0) throw new PrivilegeException(FormatError(Marshal.GetLastWin32Error())); if (LookupPrivilegeValue("", privilege, ref privilegeLUID) == 0) throw new PrivilegeException(FormatError(Marshal.GetLastWin32Error())); tokenPrivileges.PrivilegeCount = 1; tokenPrivileges.Privileges.Attributes = SE_PRIVILEGE_ENABLED; tokenPrivileges.Privileges.pLuid = privilegeLUID; int size = 4; if ( AdjustTokenPrivileges(tokenHandle, 0, ref tokenPrivileges, 4 + (12 * tokenPrivileges.PrivilegeCount), ref newPrivileges, ref size) == 0) throw new PrivilegeException(FormatError(Marshal.GetLastWin32Error())); }
private static extern int LookupPrivilegeValue(string lpSystemName, string lpName, ref LUID lpLuid);