C# - Map Network drive from Web Service

jonathanpeppers picture jonathanpeppers · Sep 16, 2009 · Viewed 10.8k times · Source

We are working on a web service that has to run a 3rd party process that interacts with a mapped network drive. So we have to map this drive programmatically from the web service.

I have already wrapped up WNetAddConnection2, etc. in a nicer class for another project, so I threw the code right in.

Our web service is running under UltiDev Cassini (instead of IIS) which runs under the System account. We get the error code for: "the specified device name is invalid" every time. I also tried impersonating other users in the web.config file, with the same results.

The drive will map just fine when I run my code from a console program under a normal user account.

I have also tried running the equivalent "net use" command from C# with the exact same results as WNetAddConnection.

Does anyone know why a windows service or System user wouldn't be able to map network drives?

Does anyone know a workaround? Simply mapping the drive on system startup would be a solution, but how could the system/impersonated user access it?

Link for UltiDev Cassini: UltiDev

SOLUTION: I set the UltiDev Cassini service to logon under Administrator and everything is working. The ASP .Net impersonation must not work as planned.

Answer

OldTroll picture OldTroll · Sep 16, 2009

If you're using the Local System account, then I believe it's inherently incapable of accessing network [foo]. I'd say impersonation is your only viable path. Technically you could reduce access controls on the share to the point that anyone could read/write to the share, but that brings more problems than solutions.