Impersonating a user in .NET isn't quite as simple as it could be. It's really easy if you you already have a WindowsIdentity or WindowsPrincipal in hand, but to get a handle on an arbitrary user you have to resort to P/Invoking the LogonUser and DuplicateToken APIs to get an impersonation context given only a username and password.
Easy enough to wrap in your own function, if you need to use it, but then you have to remember to Undo() the ImpersonationContext when you're done. Not that bad, but could be neater.
So the solution I came up with today is this:
Create a new class, call it ImpersonationContext, and add our Impersonation code in the constructor - pass the username/password as parameters. The WindowsImpersonationContext object we'll save in a private variable.
Next we'll implement IDisposable in our class and call the WindowsImpersonationContext.Undo() in the Dispose method.
What does this give us? A rather clean and readable way to run a block of code using a different security context, with automatic reversal of the impersonation when we're done.
using (new ImpersonationContext(username, password, domain)
// Run my impersonated code.
(Sorry for not bringing actual code - this was written on a closed network so I don't have the sources available)