2013-04-09 22 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