0

The question is pretty straight forward, I am making a Windows Service Program and the enviroment.getfolderpath isnt working.

Here is the code I have

string savePath = AppDomain.CurrentDomain.BaseDirectory; // this works
string savePath2 = Environment.GetFolderPath(Environment.SpecialFolder.Desktop); // this returns an empty string...but why?
Jamisco
  • 1,658
  • 3
  • 13
  • 17

1 Answers1

1

The documentation says

The path to the specified system special folder, if that folder physically exists on your computer; otherwise, an empty string ("").A folder will not physically exist if the operating system did not create it, the existing folder was deleted, or the folder is a virtual directory, such as My Computer, which does not correspond to a physical path.

When running the Service as a Local System it doesn't run with any specific user permissions. Hence the GetFolderPath is returning empty because it is not able to recognize the path Desktop for LocalSystem.

You can either use Environment.SpecialFolder.CommonDesktopDirectory which will give C:\Users\Public\Desktop or run the service with a specific user (in my case it's sampleuser) which will give the output as C:\Users\sampleuser\Desktop

enter image description here

Akshay G
  • 2,070
  • 1
  • 15
  • 33
  • AppDomain.CurrentDomain.BaseDirectory is returning the value because it knows the physical path of the Service.exe. It maybe in user's desktop folder or in some other location it will always give the output. No dependence with the Account with the service is running. – Akshay G May 20 '21 at 04:36
  • The common desktop directory works perfectly, but out of curiosity , you have any idea how I can programmatically select a user account on another computer? – Jamisco May 20 '21 at 04:47
  • 1
    u can get a list of local users https://stackoverflow.com/questions/5247798/get-list-of-local-computer-usernames-in-windows.. but if u have to select user programmatically to run the service.. you cannot.. It has to be configured while installing the service or you can change the LogOn. Once the service is started you cannot change the user for that service – Akshay G May 20 '21 at 05:08