Search code examples
visual-c++setup-projectsetup-deployment

How to detect the Program Files folder inside my executable?


My problem is, currently, all the references inside my program are using C:\\Program Files\\Myprogram folder. Is there a way that I can make my program is installable at any machine regardless where is their Program Files folder is located.

This is because some machine, has the folder at other drive eg. D:\Program Files, at Win7 machine has different name for its Program Files folder.

Need advice :)


Solution

  • Yes, hard-coding file system paths is a very bad practice, for precisely this reason. They are subject to change on different machines, and your problem shouldn't be the least bit affected because of it.

    You need to use environment variables instead. The one for the "Program Files" folder is quite simple and easy to remember. It is simply:

    %PROGRAMFILES%
    

    The Windows API provides a set of functions to retrieve the locations of these special folders, as well. Investigate the SHGetFolderPath function (or SHGetKnownFolderPath, assuming you only need to target clients running Windows Vista and above). You will need to specify the CSIDL value for the Program Files folder, CSIDL_PROGRAM_FILES. The complete list is available here.

    Sample code:

    TCHAR szPath[MAX_PATH];
    SHGetFolderPath(NULL, CSIDL_PROGRAM_FILES, NULL, 0, szPath);