C# Windows 服务 Enviroment.GetFolderPath() 返回空字符串

C# Windows Service Enviroment.GetFolderPath() returning empty string

问题很简单,我正在制作一个 Windows 服务程序,但 enviroment.getfolderpath 不工作。

这是我的代码

string savePath = AppDomain.CurrentDomain.BaseDirectory; // this works
string savePath2 = Environment.GetFolderPath(Environment.SpecialFolder.Desktop); // this returns an empty string...but why?

文档说

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.

当 运行将服务作为本地系统时,它 运行 没有任何特定的用户权限。因此 GetFolderPath 返回空,因为它无法识别 LocalSystem 的桌面路径。

您可以使用 Environment.SpecialFolder.CommonDesktopDirectory 来得到 C:\Users\Public\Desktop 或 运行 具有特定用户的服务(在我的例子中是 sampleuser),输出为 C:\Users\sampleuser\Desktop