Imagine you are going to create an application that have a method which is working with a file named Test.txt. When you run the application your code throws an error containing this message : "Access Denied on C:\Test\test.txt". After reviewing the code you find out that because the current user of windows does not have access to "C:\Test" directory. Now you want to force your application to use another User information in that block of code, we call this procedure Impersonation.
There is some classes in System.Security.Principal which helps you to achieve this goal. WindowsIdentity and WindowsImpersonationContext are two classes which we are going to use. We want to use Impersonate() method of WindowsIdentity which return a WindowsImpersonationContext. Then after you 've finished working with your file after calling Impersonate() method, you can return you current login of windows using Undo() method of your WindowsImpersonationContext instance. like this:
IntPtr accessToken = IntPtr.Zero;
....
//You have to initialize your accessToken with API calling
....
WindowsIdentity identity = new WindowsIdentity(accessToken);
WindowsImpersonationContext context = identity.Impersonate();
...
// Now your code is using the new WindowsLogin and you can do what ever this login can do
...
//Now you can return to your current login of Windows
context.Undo();
You can download the complete sample code here:
http://www.tabatabaei.info/csharpsamples/Impersonation.zip
Tuesday, June 19, 2007
Impersonation in C#
Subscribe to:
Post Comments (Atom)

9 comments:
Thanks a lot.. it was really helpful.
This is very helpful. Simple and direct, just the way I like it. I used your sample in production website where i don't have a write permission in the website folders. I used the ftp account to write the required files.
Thanks ! It's very helpful !
Thank you for this code. It has helped me .
Bless you
Zeinah
Fantastic. I have been looking for this for a while. Thank you!
I like it.
Thanks, very helpful.
hope to have a demo
Finally, someone got it right!
A lot of sites have similar code but this code actually works and is very simple to follow.
Many Thanks.
Post a Comment