6

I'm stuck with this question.

I have UNC share, I know account details, which has fullaccess, but it doesn't have access to my local system. I can get access to remote UNC with :

var token = default(IntPtr);
var context = default(WindowsImpersonationContext);
LogonUser(_config.Username, _config.Domain, _config.Password, 2, 0, out token);
context = WindowsIdentity.Impersonate(token);

//TODO :: System.IO operations
File.Copy("remote-unc-path","local-path",true); // Exception : Access is denied.

context.Undo();
CloseHandle(token);

But, I can't access my local system during Impersonation, because account doesn't have access to it.

How to copy file in this situation? Do i need to use something like buffer and turn on/off Impersonation?

Degot
  • 139
  • 4
  • 8

1 Answers1

4

What you have to do is to read all the bytes and then write them:

    var token = default(IntPtr);
    using (var context = default(WindowsImpersonationContext))
    {
       LogonUser(_config.Username, _config.Domain, _config.Password, 2, 0, out token);
       context = WindowsIdentity.Impersonate(token);
       var bytes = File.ReadAllBytes("remote-unc-path");
       context.Undo();
       CloseHandle(token);
       File.WriteAllBytes("local-path", bytes);
    }
Oskar Kjellin
  • 21,280
  • 10
  • 54
  • 93
  • But, files are huge... ~200Mb - ~1Gb.. also, this is part of system, which can have several "unc-file-storages". It will copy files in different threads... I really don't want to ReadALL for each file.. It will eat all memory – Degot Jun 28 '11 at 14:46
  • I've found a solution... Its name is WNetUseConnection – Degot Jun 28 '11 at 15:02
  • @Oskar - This used to work like a charm for me using Windows Server 2003 / IIS6.x but with Windows Server 2008 / IIS 7.5 it will only work (at least as far as I can tell) if the user has a "Local" user account on the system I'm trying to connect to. So yeah, desperately seeing a non-Administrator-account answer to this one as well. Stupid Windows security. :-\ – jerhewet Sep 12 '11 at 22:46