Gehtnet
Gehtnet

Reputation: 447

Getting path to %AppData% returns wrong value

I have a dotnet core application and I want to get the path to the local %Appdata% directory. The dotnet core application is started from a Windows Service installed previously. I used the methods decribed under this question but they all return the wrong path.

Instead of

C:\Users\MyUser\AppData\Roaming\MyApplication\file.txt

I get

C:\WINDOWS\ServiceProfiles\LocalService\AppData\Roaming\MyApplication\file.txt

1. Environment.SpecialFolder.ApplicationData

Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "MyApplication", "file.txt")

2. Environment.GetEnvironmentVariable("APPDATA")

Path.Combine(Environment.GetEnvironmentVariable("APPDATA"), "MyApplication", "file.txt")

3. Environment.ExpandEnvironmentVariables("%AppData%")

Path.Combine(Environment.ExpandEnvironmentVariables("%AppData%"), "MyApplication", "file.txt")

All methods sadly returned the wrong path. How can I get the right %AppData% path, while the application is started with a Windows Service?

Upvotes: 1

Views: 447

Answers (1)

CodeCaster
CodeCaster

Reputation: 151586

These calls don't return the wrong path. They return the AppData\Roaming path of the user under which the application is running, namely the LocalService user.

If you want to access another user's AppData, then either configure the service to run under the user whose profile you want to read from or write into, or choose a different directory and make sure the service has permissions to write there - but you really shouldn't write in another user's directories.

Upvotes: 3

Related Questions