3

I have a windows application. In that i have retrieved appdata using environment variable. So it gives me following path

c:\document and settings\current user name\application data.

But when I retrieve the appdata path from windows service using environment variable i get following path

c:\windows\ServiceProfiles\LocalService\AppData\Local

so this appdata path is different from appdata path that i got from windows application environments variable appdata path.

I m running windows service under local profile. I know that if i change service profile to run under user then service appdata path and windows application appdata path matches but service prompts for username and password.

so my question is how to get user appdata path from service by running service under local profile without prompting for username and password?

4

2 回答 2

4

我也遇到过这个问题并查看了您的问题,但乍一看我没有找到答案。

这是Mohit shah的答案

“我发现无法通过在配置文件“LocalSystem”下运行服务来从 Windows 服务获取用户 appdata 路径。所以我使用了 Environment.SpecialFolder.CommomAppData,它在 Windows 7 上运行时为我提供了应用程序数据路径 C:\ProgramData “

@Mohit Shah 请将此标记为答案,以便其他人可以从中获得帮助。

于 2014-09-02T08:12:25.663 回答
0

Windows 服务将始终在 SYSTEM 级别运行,因此它无法访问用户特定的文件夹。正如@ovais 建议的那样,您可以将用户数据存储在程序数据文件夹中,也可以使用以下方法。

您可以使用 Windows 管理 API 来获取当前的 Windows 用户名。通常剩余路径将是恒定的,因此您可以构建剩余路径。

例如,数据存储在内部 - “C:\Users\xyzUser\appdata\roaming...”

这里唯一不固定的是“xyzUser”和“C”(用户可以安装在不同的驱动器中)。

public static string GetWindowsUserAccountName()
{
string userName = string.Empty;
ManagementScope ms = new ManagementScope("\\\\.\\root\\cimv2");
ObjectQuery query = new ObjectQuery("select * from win32_computersystem");
ManagementObjectSearcher searcher = new ManagementObjectSearcher(ms, query);

foreach (ManagementObject mo in searcher?.Get())
{
userName = mo["username"]?.ToString();
}
userName = userName?.Substring(userName.IndexOf(@"\") + 1);

return userName;
}

这种方法的缺点是,当你通过远程连接连接时,用户名会给你“NULL”。所以在使用时请小心。

您可以通过以下代码段获取 Windows 文件夹。

public static string GetWindowsFolder()
{
string windowsFolder = string.Empty;
ManagementScope ms = new ManagementScope("\\\\.\\root\\cimv2");
ObjectQuery query = new ObjectQuery("SELECT * FROM Win32_OperatingSystem");
ManagementObjectSearcher searcher = new ManagementObjectSearcher(ms, query);
foreach (ManagementObject m in searcher?.Get())
{
windowsFolder = m["WindowsDirectory"]?.ToString();
}
windowsFolder = windowsFolder.Substring(0, windowsFolder.IndexOf(@"\"));
return windowsFolder;
}
于 2017-10-03T08:18:49.173 回答