GetCurrentDirectory does not really return the path of the executable file

核能气质少年 提交于 2021-02-11 15:57:44

问题


I am coding a program as service using c++, when I test it as a normal program, the function GetCurrentDirectory returns the correct path. But when I try to install my program as service, GetCurrentDirectory returns C:\Windows\System32 instead of the path of the executable.

How can I get the path of my executable file in a way that will work for a service?


回答1:


Working directory for Windows services is always %WINDIR%\System32.

To get directory, where your executable resides, simply call GetModuleFileName with NULL for hModule argument, and manually strip executable name.




回答2:


Because %WinDir%\System32 is the default working directory for a 32/64 bit Windows service (%WinDir%\SysWOW64 for 32 bit services on 64 bit Windows).

You may set working directory of your service to something else, see also Windows Service: Can I configure the current working directory? or - better - do not rely in your code about working directory. Few options:

  • Read it from registry: HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\services\<service name>\ImagePath.
  • Use WMI to enumerate services (if you really want to...)
  • Use GetModuleFileName(). It's easy to use but be careful: it has some tricky behavior with WOW64, some virtualization environments and for svcshot hosted services (it's little bit old but you may want to read this article.)
  • Use QueryServiceConfig().

What I'd suggest:

  • Save/load your data in a shared known folder, for example for Common Application Data: SHGetFolderPath(NULL, CSIDL_COMMON_APPDATA, NULL, 0, szPath).


来源:https://stackoverflow.com/questions/40841907/getcurrentdirectory-does-not-really-return-the-path-of-the-executable-file

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!