GetCurrentDirectory 并不是真正的 return 可执行文件的路径

GetCurrentDirectory does not really return the path of the executable file

我正在使用 C++ 将程序编码为服务,当我将其作为普通程序进行测试时,函数 GetCurrentDirectory returns 路径正确。但是当我尝试将我的程序安装为服务时,GetCurrentDirectory returns C:\Windows\System32 而不是可执行文件的路径。

如何以适用于服务的方式获取我的可执行文件的路径?

Windows 服务的工作目录总是 %WINDIR%\System32

要获取可执行文件所在的目录,只需调用 GetModuleFileName 并为 hModule 参数设置 NULL,然后手动删除可执行文件名称。

因为 %WinDir%\System32 是 32/64 位 Windows 服务的默认工作目录(%WinDir%\SysWOW64 用于 64 位 Windows 上的 32 位服务)。

您可以将服务的工作目录设置为其他内容,另请参阅 Windows Service: Can I configure the current working directory? 或者 - 更好 - 不要在代码中依赖工作目录。几个选项:

  • 从注册表中读取:HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\services\<service name>\ImagePath
  • 使用 WMI 枚举服务(如果你真的想...)
  • 使用GetModuleFileName()。它易于使用但要小心:它在 WOW64、一些虚拟化环境和 svcshot 托管服务中有一些棘手的行为(它 有点 旧但你可能想阅读 this article.)
  • 使用QueryServiceConfig().

我的建议:

  • Save/load 您的数据位于共享的已知文件夹中,例如通用应用程序数据:SHGetFolderPath(NULL, CSIDL_COMMON_APPDATA, NULL, 0, szPath).