views:

55

answers:

4

I have a C++ Windows service, and I would like to access an executable in the same directory as the service's executable (via the system function). I'd imagine to do this I'll need to find that directory, so that I can refer to the target executable's path. How can I find the directory in which the service is installed, in code?

+1  A: 

You can use the GetModuleFileName function. See the Installing a Service example.

Garett
+2  A: 

Depends.

If it's from within the service you can always use GetModuleFileName, which produces a fully qualified path.

If it's from another program, then since it is service you can inspect the service's registry information.

Alf P. Steinbach
+2  A: 

As others have mentioned, GetModuleFileName() can do that job but YMMV. The most reliable way is to read this information from the registry key HKLM\System\CurrentControlSet\Services\%ServiceName%\ImagePath where %ServiceName% is a name of your service.

For an example of reading the registry using C++ check this out.

Good luck!

Vlad Lazarenko
+2  A: 

You can use the QueryServiceConfig() function. The path to the binary is stored in the lpBinaryPathName field of the QUERY_SERVICE_CONFIG structure.

Ferruccio
+1 - this is the best way to get the 'official' information
Steve Townsend
This function actually does get information from the registry. But the problem is that you have to have a service handle, which I don't like at all. Service name should be enough.
Vlad Lazarenko
@Vlad: if you go the registry route, you will need a handle to a registry key. Most things in the Windows API are accessed through handles.
Ferruccio