模仿用户时出现BadImageFormatException

时间:2014-03-26 10:05:14

标签: c# .net code-access-security

我试图通过以下代码从Windows窗体应用程序模拟用户:

public void Impersonate()
{
    //elevate privileges before doing file copy to handle domain security
    WindowsImpersonationContext impersonationContext = null;
    IntPtr userHandle = IntPtr.Zero;
    const int LOGON32_PROVIDER_DEFAULT = 0;
    const int LOGON32_LOGON_INTERACTIVE = 2;
    string domain = ConfigurationManager.AppSettings["ImpersonationDomain"];
    string user = ConfigurationManager.AppSettings["ImpersonationUser"];
    string password = ConfigurationManager.AppSettings["ImpersonationPassword"];

    try
    {
        // if domain name was blank, assume local machine
        if (domain == "")
            domain = System.Environment.MachineName;

        // Call LogonUser to get a token for the user
        bool loggedOn = LogonUser(user,
                                    domain,
                                    password,
                                    LOGON32_LOGON_INTERACTIVE,
                                    LOGON32_PROVIDER_DEFAULT,
                                    ref userHandle);

        if (!loggedOn)return;

        // Begin impersonating the user
        impersonationContext = WindowsIdentity.Impersonate(userHandle);

        PrintReceipt();
    }
    catch (Exception ex)
    {
        MessageBox.Show("Exception impersonating user: " + ex.Message);
    }
    finally
    {
        // Clean up
        if (impersonationContext != null)
        {
            impersonationContext.Undo();
        }

        if (userHandle != IntPtr.Zero)
        {
            CloseHandle(userHandle);
        }
    }
}

程序通过指向网络共享的快捷方式启动,机器运行Windows7 32位。

但程序在行上抛出BadImageFormatException:

impersonationContext = WindowsIdentity.Impersonate(userHandle);

完全相同的代码可以在控制台应用程序中运行,并且我已经尝试将exe编译为'任何CPU'和x86。

我没有线索,有人知道可以做些什么吗?

0 个答案:

没有答案