从Windows服务获取用户根目录

exv*_*nce 5 .net c# windows

我有一个用C#编写的Windows服务.我需要在每个用户目录中添加一个文件.我怎样才能找到入路?我意识到这真的很愚蠢,但这正是我目前正在做的事情:

  if (Directory.Exists("C:\\Users"))
  {
    path = "C:\\Users";
  }
  else if (Directory.Exists("C:\\Documents and Settings"))
  {
    path = "C:\\Documents and Settings";
  }
Run Code Online (Sandbox Code Playgroud)

我查看了特殊文件夹:http://msdn.microsoft.com/en-us/library/system.environment.specialfolder.aspx

他们似乎没有回报我需要的东西.例如,ApplicationData正在返回System32目录的路径.我认为这是因为它作为Windows服务运行.我目前使用的代码适用于我所做的少数测试.看起来应该有更智能(防错)的方式来获得这条路径.

另一个想法......也许有一个注册表项会给我我想要的东西?嗯

小智 1

我在Win7注册表下发现了这个。XP 看起来具有相同的注册表项,但这些值中包含“所有用户”配置文件。

[HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\Shell Folders]
"Common Desktop"="C:\\Users\\Public\\Desktop"
"Common Start Menu"="C:\\ProgramData\\Microsoft\\Windows\\Start Menu"
"CommonVideo"="C:\\Users\\Public\\Videos"
"CommonPictures"="C:\\Users\\Public\\Pictures"
"Common Programs"="C:\\ProgramData\\Microsoft\\Windows\\Start Menu\\Programs"
"CommonMusic"="C:\\Users\\Public\\Music"
"Common Administrative Tools"="C:\\ProgramData\\Microsoft\\Windows\\Start Menu\\Programs\\Administrative Tools"
"Common Startup"="C:\\ProgramData\\Microsoft\\Windows\\Start Menu\\Programs\\Startup"
"Common Documents"="C:\\Users\\Public\\Documents"
"OEM Links"="C:\\ProgramData\\OEM Links"
"Common Templates"="C:\\ProgramData\\Microsoft\\Windows\\Templates"
"Common AppData"="C:\\ProgramData"
Run Code Online (Sandbox Code Playgroud)

  • 服务不是在用户上下文中运行的,那么这个环境变量是如何存在的呢? (2认同)