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.
Today 7 years later I'm facing the same issue and I'd like to share my version of the solution.
It is copy & paste ready :-) Here it is:
Step 1
In your code (whenever you need to do something with permissions)
Step 2
The Helper file which does a magic
One option that might work is using
WindowsIdentity.Impersonate
(and change the thread principal) to become the desired user, like so. Back to p/invoke, though, I'm afraid...Another cheeky (and equally far from ideal) option might be to spawn a process to do the work...
ProcessStartInfo
accepts a.UserName
,.Password
and.Domain
.Finally - perhaps run the service in a dedicated account that has access?(removed as you have clarified that this isn't an option).For VB.lovers the VB.NET equivalent of Luke Quinane's code (thanks Luke!)
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):
You should be looking at adding a like like this:
Into your web.config.
More Information.