Is it possible to open excel interop in C# with impersonation. I want to open excel application to run under different account other than the one which C# program runs in. By default, it opens under same user account that runs C# program.
MyApp = new Excel.Application();
MyApp.Visible = false;
MyApp.DisplayAlerts = false;
MyBook = MyApp.Workbooks.Open(@"C:\Sample.xlsx");
Any other way to do this also welcomed.
In order to obtain an impersonation context from code behind you can use some unmanaged functions from advapi32.dll
.
LogonUser
in order to obtain a user tokenWindowsIdentity
based on the user tokenImpersonate
on the windows identity. This will return an WindowsImpersonationContext
that can be used later to Undo
impersonationctx.Undo();
) and release resources.What a mess, don't you think?
Fortunately you don't have to reinvent the wheel again. Uwe Keim wrote a class that does all the above steps under the hood while maintaining reusability.
A small C# class for impersonating a user
using ( new Impersonator( "username", "domainName", "password" ) )
{
/* code that executes under the new context */
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.