Search code examples
c#.netwinapinetwork-programmingpasswords

How to provide user name and password when connecting to a network share


When connecting to a network share for which the current user (in my case, a network enabled service user) has no rights, name and password have to be provided.

I know how to do this with Win32 functions (the WNet* family from mpr.dll), but would like to do it with .Net (2.0) functionality.

What options are available?

Maybe some more information helps:

  • The use case is a windows service, not an Asp.Net application.
  • The service is running under an account which has no rights on the share.
  • The user account needed for the share is not known on the client side.
  • Client and server are not members of the same domain.

Solution

  • You can either change the thread identity, or P/Invoke WNetAddConnection2. I prefer the latter, as I sometimes need to maintain multiple credentials for different locations. I wrap it into an IDisposable and call WNetCancelConnection2 to remove the creds afterwards (avoiding the multiple usernames error):

    using (new NetworkConnection(@"\\server\read", readCredentials))
    using (new NetworkConnection(@"\\server2\write", writeCredentials)) {
       File.Copy(@"\\server\read\file", @"\\server2\write\file");
    }