I am try to get C:\Users\<username>\AppData\Local
folder path using
Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData)
in a C# Windows service, but it returns some other path
C:\Windows\ServiceProfiles\LocalService\AppData\Local
Does any have any idea how to do it correctly?
Run a command shell (start/Run, then "cmd") and type "set". This will list all the environmental variables available. Having said that, USERPROFILE is perfectly valid. There's also APPDATA and LOCALAPPDATA.
Are you running the service under a user account? If not, the service will use its own profile as you see. If this service is "logged into" by a user, then you could pass the folder to the service and bypass local checking. Otherwise, try running the service under a user account (or create an account for it).
The AppData folder for each user is stored in the registry.
Using this path:
const string regKeyFolders = @"HKEY_USERS\<SID>\Software\Microsoft\Windows\CurrentVersion\Explorer\Shell Folders";
const string regValueAppData = @"AppData";
Given a variable sid string containing the users sid, you can get their AppData path like this:
string path=Registry.GetValue(regKeyFolders.Replace("<SID>", sid), regValueAppData, null) as string;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With