Copy file on a network shared drive

Martin Delille picture Martin Delille · Sep 16, 2009 · Viewed 80.4k times · Source

I have a network shared drive ("\serveur\folder") on which I would like to copy file. I can write on the drive with a specific user ("user"/"pass"). How can I access the shared drived with write privilege using C#?

Answer

Mitch Wheat picture Mitch Wheat · Sep 16, 2009

Untested code, but it will be similiar to:

AppDomain.CurrentDomain.SetPrincipalPolicy(PrincipalPolicy.WindowsPrincipal);

// http://pinvoke.net/default.aspx/advapi32/LogonUser.html    
IntPtr token;
LogonUser("username", "domain", "password", LogonType.LOGON32_LOGON_BATCH, LogonProvider.LOGON32_PROVIDER_DEFAULT);

WindowsIdentity identity = new WindowsIdentity(token);

WindowsImpersonationContext context = identity.Impersonate();

try
{
    File.Copy(@"c:\temp\MyFile.txt", @"\\server\folder\Myfile.txt", true);
}
finally
{
    context.Undo();
}