問題
使用 advapi32.dll強制變更程式執行權限
解決方法
WindowsImpersonationContext context; [DllImport("advapi32.dll", SetLastError = true)] public static extern bool LogonUser(String Username, String Domain, String Password, int LogonType, int LogonProvider, ref IntPtr token); [DllImport("kernel32.dll", CharSet = CharSet.Auto)] public extern static bool CloseHandle(IntPtr handle); private void GetPermission() { IntPtr tokenHandle = IntPtr.Zero; try { IntPtr dupeTokenHandle = new IntPtr(0); const int LOGON32_PROVIDER_DEFAULT = 0; //This parameter causes LogonUser to create a primary token. const int LOGON32_LOGON_INTERACTIVE = 2; // Call LogonUser to obtain a handle to an access token. bool returnValue = LogonUser("admin", "misteam", "123456", LOGON32_LOGON_INTERACTIVE, LOGON32_PROVIDER_DEFAULT, ref tokenHandle); if (returnValue == true) { WindowsIdentity newId = new WindowsIdentity(tokenHandle); WindowsImpersonationContext user = newId.Impersonate(); /* do somthing */ } else { throw new Exception("Login user failed"); } } finally { // Free the tokens. if (tokenHandle != IntPtr.Zero) CloseHandle(tokenHandle); } }
沒有留言:
張貼留言