Wednesday, June 27, 2012

Copy a network (shared folder) file using c#

Recently I came across a requirement to copy a network file (shared folder file) in regular time interval. I tried many options. Finally following approach worked properly.

We can do following-
  1. Login to a user account using c#.
  2. Impersonate as the logged in user.
  3. Copy the file using System.IO.File.Copy.

For step 1 we can login to a user account using LogonUser of advapi32.dll. To consume this method we need to do dll import as follows. We can add the following method in the current class-
[System.Runtime.InteropServices.DllImport("advapi32.dll", SetLastError = true, CharSet = System.Runtime.InteropServices.CharSet.Unicode)]
public static extern bool LogonUser(String lpszUsername, String lpszDomain, String lpszPassword, int dwLogonType, int dwLogonProvider, ref IntPtr phToken);
We can see the detail of the method here-

Next we can call the method like below-
IntPtr tokenHandle = new IntPtr(0);
bool returnValue = LogonUser("usermane", "domain", "password", 2, 0, ref tokenHandle);
if (!returnValue)
throw new Exception("Logon failed.");
For step 2 we can impersonate the logon user by the Impersonate method of WindowsIdentity class as follows-
System.Security.Principal.WindowsImpersonationContext impersonatedUser = null;
System.Security.Principal.WindowsIdentity wid = new System.Security.Principal.WindowsIdentity(tokenHandle);
impersonatedUser = wid.Impersonate();
And finally for step 3 we can copy the file as-
System.IO.File.Copy("SourceFile", "DestinationFile", true);
For source and the destination file either a network file or a local file. We also need to take care of proper access right of the shared folder.


  1. error in this code " server could not be contacted"

  2. Shared folder nay not be there or there can be permission issue.