是否可以让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,那么第二次调用(在块内)不会失败,但会返回原始用户的路径。
答案 0 :(得分:1)
要完成这项工作需要做一些事情:
这是一个很好的示例,展示了如何调用LoadUserProfile API - http://www.codeproject.com/Articles/125810/A-complete-Impersonation-Demo-in-C-NET