May 4, 2010 by Christoff Truter C#
The WindowsImpersonationContext class provides us with the ability to impersonate an user.
In the following post we're going to look at how to write to a protected shared folder
using impersonation.
You will notice that the WindowsImpersonationContext class doesn't have a constructor, nor
any static methods defined - one can however get an instance of this class via the Impersonate static
method in the WindowsIdentity class, observe:
using (WindowsImpersonationContext context = WindowsIdentity.Impersonate(token)) { // Some operation requiring impersonation }
[DllImport("advapi32.dll", SetLastError = true)] public static extern bool LogonUser(string lpszUsername, string lpszDomain, string lpszPassword, int dwLogonType, int dwLogonProvider, ref IntPtr phToken);
[DllImport("kernel32.dll")] public static extern bool CloseHandle(IntPtr token);
enum LogonType { Interactive = 2, Network = 3, Batch = 4, Service = 5, Unlock = 7, NetworkClearText = 8, NewCredentials = 9 } enum LogonProvider { Default = 0, WinNT35 = 1, WinNT40 = 2, WinNT50 = 3 }
IntPtr token = IntPtr.Zero; bool valid = LogonUser("username", "yourdomain.com", "password", (int)LogonType.Interactive, (int)LogonProvider.Default, ref token); if (valid) { using (WindowsImpersonationContext context = WindowsIdentity.Impersonate(token)) { CloseHandle(token); File.WriteAllBytes(@"\\yourserver\someshare\test.txt", new byte[] { }); } }
IntPtr token = IntPtr.Zero; LogonUser("username", "yourdomain.com", "password", (int)LogonType.NewCredentials, (int)LogonProvider.WinNT50, ref token); using (WindowsImpersonationContext context = WindowsIdentity.Impersonate(token)) { CloseHandle(token); File.WriteAllBytes(@"\\yourserver\someshare\test.txt", new byte[] { }); }
Excellent !! January 19, 2021 by Rajesh
This worked perfectly to me. Thank a lot :)