0
我想運行提升的命令提示符進程。我有用戶:myDomain \ myAdmin和myDomain \ myUser。運行提升的命令提示符進程
如果我運行下myDomain \ myAdmin下的代碼,它工作正常。但在myDomain \ myUser下,出現下一個異常:「未知錯誤(0xfffffffe)」。 任何想法爲什麼?
namespace myProcess
{
public partial class Form1 : Form
{
[DllImport("advapi32.dll", SetLastError = true, CharSet = CharSet.Unicode)]
public static extern bool LogonUser(String lpszUsername, String lpszDomain, String lpszPassword,
int dwLogonType, int dwLogonProvider, out SafeTokenHandle phToken);
[DllImport("kernel32.dll", CharSet = CharSet.Auto)]
public extern static bool CloseHandle(IntPtr handle);
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
try
{
SafeTokenHandle safeTokenHandle;
string userName = "myAdmin", domainName = "myDomain", password = "Password";
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(userName, domainName, password, LOGON32_LOGON_INTERACTIVE, LOGON32_PROVIDER_DEFAULT, out safeTokenHandle);
if (returnValue)
{
using (safeTokenHandle)
{
txtLogs.Text += "\r\nBefore: " + WindowsIdentity.GetCurrent().Name;
// Use the token handle returned by LogonUser.
using (WindowsIdentity newId = new WindowsIdentity(safeTokenHandle.DangerousGetHandle()))
{
using (WindowsImpersonationContext impersonatedUser = newId.Impersonate())
{
txtLogs.Text += "\r\nImpersonation: " + WindowsIdentity.GetCurrent().Name;
RunProcess();
}
}
// Releasing the context object stops the impersonation - check the identity.
txtLogs.Text += "\r\nAfter: " + WindowsIdentity.GetCurrent().Name;
}
}
else
{
int ret = Marshal.GetLastWin32Error();
txtLogs.Text += "\r\nLogonUser failed with error code: " + ret;
}
}
catch (Exception ex)
{
txtLogs.Text += "\r\nMAIN: " + ex.Message;
}
}
private void RunProcess()
{
try
{
ProcessStartInfo proc = new ProcessStartInfo();
proc.UseShellExecute = true;
proc.FileName = "cmd.exe";
proc.Verb = "runas";
proc.LoadUserProfile = true;
Process p = Process.Start(proc);
}
catch (Exception ex)
{
txtLogs.Text += "\r\n" + ex.Message;
}
}
}
public sealed class SafeTokenHandle : SafeHandleZeroOrMinusOneIsInvalid
{
private SafeTokenHandle() : base(true)
{
}
[DllImport("kernel32.dll")]
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
[SuppressUnmanagedCodeSecurity]
[return: MarshalAs(UnmanagedType.Bool)]
private static extern bool CloseHandle(IntPtr handle);
protected override bool ReleaseHandle()
{
return CloseHandle(handle);
}
}
}
調試器告訴你什麼時候你通過代碼? –
出於好奇,你爲什麼試圖登錄到管理員帳戶? 'myUser'是否需要密碼才能以管理員權限運行應用程序?如果是這樣,也許你應該嘗試'CreateProcessAsUser()'而不是? –
如果您可以提供更多詳細信息 - 比如您已記錄的完整消息列表,那該多好。或者例外情況發生。這聽起來像你對'Process.Start()'的調用失敗了。 – user314104