windowsnetwork-programmingservicedirectoryshared

How do I get a windows service to have access to a shared network folder?


I have a windows service that will be running on a client server. This service needs to access 2 folders that are located in different shared folders (Y:\ and Z:\ ) which are both on separate computers (3 computers total).

Currently the service is only able to see files located on the same machine. When I do a IO.Directory.Exists() on the shared folders, it returns false.

Here are things I have tried:

  1. Running as a Network Service
  2. Running as a Local System
  3. Running as a Local Service
  4. testing existence with \\192.168.1.xx\path\to\folder
  5. testing existence with Y:\ and Z:\
  6. Creating a user on the other computers with the same Username and Password
  7. Verifying the folders gave full access to everyone

Nothing yet has worked, any help is much appreciated.


Solution

  • In an Active Directory environment, Network Service and Local System both have network access to other machines in the domain; the server just needs to be configured to grant access to the client's computer account in the domain, i.e., the COMPUTERNAME$ account. If you use a UNC path the connection will be established automatically. You still can't use drive letters established in another logon session, but in most circumstances the UNC path will do.

    In a stand-alone environment it's a bit trickier. The only reliable approach is to establish the network connection explicitly, which you can do using WNetAddConnection2 or any of the various alternatives. (Or if you can't call the Win32 API, you can shell out to the net use command.) In either case, once the connection is established you can use a UNC path. There is typically no need to map a drive letter.

    If you must have a drive letter for some reason, it is usually best to use the WNetUseConnection function instead of WNetAddConnection2. That can be configured to select a drive letter automatically, so you don't have to try to figure out which letters are already in use.

    Note that depending on the circumstances, it may be necessary to use the long form of the username for the account on the server, i.e., SERVERNAME\USERNAME or DOMAINNAME\USERNAME if it is a domain account. Windows 10 clients seem particularly fussy about this for some reason.