One of the features of the ASP.NET application that I am currently working on requires copying dynamically generated files to a network share path. As guessed(!), the user identity of the ASP.NET worker process (IIS application pool, in case of Windows 2003) did not have the required privileges to the network path, causing the familiar “access denied” exception. The solution is pretty obvious: impersonate the file copying code with an user account that has necessary access rights to the share. Here is the pretty straight forward code for everyone’s benefit:

using System.Runtime.InteropServices;
using System.IO;
using System.Security.Principal;
[DllImport ("advapi32.dll", SetLastError = true)]
private static extern bool LogonUser (string lpszUsername, string lpszDomain, string lpszPassword, int dwLogonType, int dwLogonProvider, out IntPtr phToken);
[DllImport ("kernel32.dll", CharSet = CharSet.Auto)]
private extern static bool CloseHandle (IntPtr handle);
IntPtr token;
WindowsIdentity wi;
if (LogonUser ("<user name with network share access>",
    "<domain name>",
    "<user password>",
    out token))
    wi = new WindowsIdentity (token);
    WindowsImpersonationContext wic = wi.Impersonate ();
    File.Copy (@"<file source>", @"<network share/UNC path>");     wic.Undo ();     CloseHandle (token); } else {     Console.WriteLine ("LogonUser() failed with error code " + Marshal.GetLastWin32Error ()); }