简体   繁体   中英

Open excel interop with impersonation in C#

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 .

  • Call LogonUser in order to obtain a user token
  • Create a WindowsIdentity based on the user token
  • Call Impersonate on the windows identity. This will return an WindowsImpersonationContext that can be used later to Undo impersonation
  • Call your code here.
  • Undo the impersonation ( ctx.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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM