7

In c# 2008, I'm trying to copy a file to a destination path (for example \newserver\destinationFolder), that can be in another domain or using a different username/password than the current user. How can I specify these new network credentials before doing the File.Copy(...) ?

Thank you!

dbc
  • 104,963
  • 20
  • 228
  • 340
Cedric
  • 73
  • 1
  • 3
  • 1
    possible duplicate of http://stackoverflow.com/questions/158492/c-network-login – Anders Abel Apr 30 '10 at 13:59
  • Related or duplicate: [How to provide user name and password when connecting to a network share](https://stackoverflow.com/q/295538/3744182), [copy files with authentication in c#](https://stackoverflow.com/q/17786037/3744182), [Copying files over network (requiring authentication)](https://stackoverflow.com/q/2715625/3744182). – dbc Mar 06 '21 at 22:31

3 Answers3

2

Good question but I dont think this is possible. I believe this type of file copy from one domain to another ( where there is not a trust set up) would be considered security hole.

Some options:

  1. Set up a trust between the domains and give rights to the current user
  2. You could try a Shell execute command and see if you can make this work through command line parameters. I was thinking "Net use" command.
John Hartsock
  • 85,422
  • 23
  • 131
  • 146
1

Look at LogonUser. Here's the pinvoke page for it:

http://www.pinvoke.net/default.aspx/advapi32.logonuser

Hans Olsson
  • 54,199
  • 15
  • 94
  • 116
0

MapDrive => Copy files as local user => UnmapDrive. Take a look here:

    protected int MapDrive(){
        NETRESOURCEA[] resources = new NETRESOURCEA[1];
        resources[0] = new NETRESOURCEA();
        resources[0].dwType = 1;
        int dwFlags = 1;
        resources[0].lpLocalName = _DriveLetter;
        resources[0].lpRemoteName = _Path;
        resources[0].lpProvider = null; 
        int ret = WNetAddConnection2A(resources, null, null, dwFlags);
        return ret;
    }

    protected int UnmapDrive()
    {
        int ret = WNetCancelConnection2A(_DriveLetter, 0, true);
        return ret;
    }
Vivek
  • 16,360
  • 5
  • 30
  • 37