2013-04-09 70 views
1

是否有可能获得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

有需要的情况发生,使这项工作的几件事情:

  1. 模拟用户的配置文件需要使用LoadUserProfile明确加载 - 只是通过模拟用户没有这样做。请注意,此API要求调用进程必须具有SE_RESTORE_NAME和SE_BACKUP_NAME权限。
  2. 如果使用的是从ApplicationSettingsBase继承的设置类,则需要实现自定义SettingsProvider知道如何加载配置每个用户
  3. 的​​。您需要自定义getter来每次强制执行Reload()以确保SettingsProvider被调用。

这是展示如何调用LoadUserProfile API一个很好的样本 - http://www.codeproject.com/Articles/125810/A-complete-Impersonation-Demo-in-C-NET