在 C# windows 服务中获取 appdata\local 文件夹路径

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11201308/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-09 16:57:14  来源:igfitidea点击:

Get appdata\local folder path in C# windows service

c#windows-services

提问by AMIT SHELKE

I am try to get C:\Users\<username>\AppData\Localfolder path using

我尝试使用获取C:\Users\<username>\AppData\Local文件夹路径

Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData)

in a C# Windows service, but it returns some other path

在 C# Windows 服务中,但它返回一些其他路径

C:\Windows\ServiceProfiles\LocalService\AppData\Local

Does any have any idea how to do it correctly?

有没有人知道如何正确地做到这一点?

回答by Wolf5370

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

您是否在用户帐户下运行该服务?如果没有,服务将使用自己的配置文件,如您所见。如果此服务由用户“登录”,则您可以将该文件夹传递给该服务并绕过本地检查。否则,请尝试在用户帐户下运行该服务(或为其创建一个帐户)。

回答by Derrick

The AppData folder for each user is stored in the registry.

每个用户的 AppData 文件夹都存储在注册表中。

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:

给定一个包含用户 sid 的变量 sid 字符串,您可以像这样获取他们的 AppData 路径:

string path=Registry.GetValue(regKeyFolders.Replace("<SID>", sid), regValueAppData, null) as string;