带模拟的用户设置/配置

时间:2013-04-09 02:11:01

标签: .net winforms impersonation

是否可以让ConfigurationManager.OpenExeConfiguration使用当前模拟的用户(模拟的时间类似于WindowsImpersonationContext的代码示例) - 以下是一个小提取?

using (safeTokenHandle)
{
    Console.WriteLine("Did LogonUser Succeed? " + (returnValue ? "Yes" : "No"));
    Console.WriteLine("Value of Windows NT token: " + safeTokenHandle);

    // Check the identity.
    Console.WriteLine("Before impersonation: "
        + WindowsIdentity.GetCurrent().Name);

    Configuration config;
    //config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.PerUserRoamingAndLocal);
    //Console.WriteLine("Local user config path: {0}", config.FilePath);

    // Use the token handle returned by LogonUser. 
    using (WindowsIdentity newId = new WindowsIdentity(safeTokenHandle.DangerousGetHandle()))
    {
        using (WindowsImpersonationContext impersonatedUser = newId.Impersonate())
        {

            // Check the identity.
            Console.WriteLine("After impersonation: " + WindowsIdentity.GetCurrent().Name);

            // This line throws exception
            config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.PerUserRoamingAndLocal);
            Console.WriteLine("Local user config path: {0}", config.FilePath);

        }
    }
    // Releasing the context object stops the impersonation 
    // Check the identity.
    Console.WriteLine("After closing the context: " + WindowsIdentity.GetCurrent().Name);
}

如果我只是在模拟范围内添加调用,则会抛出异常:

Exception occurred. An error occurred loading a configuration file: Catastrophic failure (Exception from HRESULT: 0x8000FFFF (E_UNEXPECTED))

如果我还在模拟块之前调用OpenExeConfiguration,那么第二次调用(在块内)不会失败,但会返回原始用户的路径。

1 个答案:

答案 0 :(得分:1)

要完成这项工作需要做一些事情:

  1. 需要使用LoadUserProfile显式加载模拟用户的个人资料 - 这不是仅通过模仿用户来完成的。请注意,此API要求调用进程必须具有SE_RESTORE_NAME和SE_BACKUP_NAME权限。
  2. 如果使用继承自ApplicationSettingsBase的Settings类,则需要实现知道如何加载每用户配置的自定义SettingsProvider
  3. Settings properties by default are cached。您需要自定义getter以每次强制重新加载()以确保调用SettingsProvider。
  4. 这是一个很好的示例,展示了如何调用LoadUserProfile API - http://www.codeproject.com/Articles/125810/A-complete-Impersonation-Demo-in-C-NET

相关问题