public void Dispose() { if (IntPtr.Zero != hToken) { SetPrivilege(false); UnsafeMethods.CloseHandle(hToken); hToken = IntPtr.Zero; } }
public Privilege(string name) { this.name = name; IntPtr hThread = UnsafeMethods.GetCurrentThread(); if (!UnsafeMethods.OpenThreadToken(hThread, UnsafeMethods.TOKEN_ADJUST_PRIVILEGES | UnsafeMethods.TOKEN_QUERY, false, out hToken)) { int error = Marshal.GetLastWin32Error(); if (error != UnsafeMethods.ERROR_NO_TOKEN) { throw new Win32Exception(error); } if (!UnsafeMethods.ImpersonateSelf(UnsafeMethods.SECURITY_IMPERSONATION_LEVEL.SecurityImpersonation)) { error = Marshal.GetLastWin32Error(); throw new Win32Exception(error); } if (!UnsafeMethods.OpenThreadToken(hThread, UnsafeMethods.TOKEN_ADJUST_PRIVILEGES | UnsafeMethods.TOKEN_QUERY, false, out hToken)) { error = Marshal.GetLastWin32Error(); throw new Win32Exception(error); } } if (!SetPrivilege(true)) { int error = Marshal.GetLastWin32Error(); UnsafeMethods.CloseHandle(hToken); hToken = IntPtr.Zero; throw new Win32Exception(error); } }