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
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.