by Marcel Wijnands
8. August 2008 23:49
As an addition to my previous post, I wrote a little Class that makes it very easy and safe to execute a piece of code as a different user in ASP.NET (of course it works in Forms as well). Because it implements the IDisposable interface, you can use a Using block in which the code is executed as the supplied user like this;
Using (New Impersonator("DOMAIN", "UserName", "Password"))
For Each File As String In System.IO.Directory.GetFiles("\\SOMESERVER\SomeShare")
Response.Write(File)
Response.Write("<br />")
Next
End Using
If you need to do this often in your application, and decide to keep a WindowsIdentity somewhere like I demonstrated in my previous post (to increase performance), you can use the other Constructor of the Impersonator Class.
First you can use the Shared Function of the Impersonation Class to get a WindowsIdentity;
Application("FixedIdentity") = Impersonator.GetFixedIdentity("DOMAIN", "UserName", "Password")
Now use the other Constructor;
' Get the WindowsIdentity from where you keep it (in this case the Application Class).
Dim FixedIdentity As WindowsIdentity = Application("FixedIdentity")
Using (New Impersonator(FixedIdentity))
For Each File As String In System.IO.Directory.GetFiles("\\SOMESERVER\SomeShare")
Response.Write(File)
Response.Write("<br />")
Next
End Using
Nice and simple! Download it below:
Impersonator.zip (1.06 kb)
The idea is based on the C# Impersonator Class written by Uwe Keim.