Windows – Correct way to access a network share in a Windows service

local-systemnet-usenetwork-shareservicewindows

I have a Windows service which requires on-demand access to a remote CIFS share. Whenever it needs to access the share, it first tries to 'mount' it with provided credentials,

NET USE \\host\share password /USER:user

uses the share's contents, and then removes the share.

NET USE \\host\share /DELETE

Currently, the service only works the first time the share is used. On subsequent attempts, it doesn't work and I get the following error:

NET failed with exit code 2

However, this same logic all works perfectly fine when run manually from the command line; it only fails in the context of the service.

My question is: is there a better, more correct way to handle network shares in a Windows service? According to this article, NET USE is not recommended for use in services, even without the use of drive letters. Is there some alternative to NET USE I should be using, or does the service just need to run as a user other than the default LocalSystem user?

Ideally, the share should only be accessible when directly needed; so I'd like to keep the logic where the share gets deleted every time if possible.

Best Answer

You should be running the service as a specific user account, and that user account should have permissions to access the share.

Putting a username and password in like that is a pretty awful way of working. Not only for security, but also for portability and management.