Using Impersonation in VB.Net
Home | About Us | Products | Support | Contact Us | Library
How to impersonate a specific user
You'll be surprised at how frequently the ability to impersonate a user account comes up, especially in a product like ArchiverFS (details of which can be found here). VB.NET has made lots of thing really easy, and one of them is running software under the credentials of the logged in user. It really is just a few lines of code to impersonate the logged in users credentials.Dim impersonationContext As System.Security.Principal.WindowsImpersonationContext
Dim currentWindowsIdentity As System.Security.Principal.WindowsIdentity
currentWindowsIdentity = CType(System.Security.Principal.WindowsIdentity.GetCurrent, System.Security.Principal.WindowsIdentity) impersonationContext =
currentWindowsIdentity.Impersonate()
That starts off the impersonation and you can now run any code you need to under the users credentials. When you have finished with the processes you needed to impersonate the logged in user for you should end the impersonation...
impersonationContext.Undo()
Impersonation of a logged in user is a very expensive process comparatively, so it should only ever be applied where it is actually needed.