开发者

How to detect the Program Files folder inside my executable?

开发者 https://www.devze.com 2023-02-10 14:24 出处:网络
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 machi

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 :)


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);


If using Visual C++ .NET, you can use GetFolderPath:

// Sample for the Environment::GetFolderPath method
#using <mscorlib.dll>

using namespace System;

int main() {
   Console::WriteLine(S"GetFolderPath: {0}",
      Environment::GetFolderPath(Environment::SpecialFolder::ProgramFiles));
   return 0;
}


Microsoft has about a half dozen different answers to this question. I believe the one they favor at the moment is SHGetKnownFolderPath. Depending on how old of Windows versions you care about, you may also want to look at SHGetFolderPath or SHGetSpecialFolderPath.


If you're writing your program in C/C++, you can use the SHGetFolderPath function as specified at http://msdn.microsoft.com/en-us/library/bb762181(VS.85).aspx. Vista and newer have newer APIs, but this one is still around for backward compatibility.

From a Visual Studio command prompt, you can build and run this to try it out.

// Build with:
// cl sample.cpp /link Shell32.lib

#include <stdio.h>
#include <Shlobj.h>

void main()
{
  char path[MAX_PATH];
  HRESULT hr = SHGetFolderPath(
    0,                   // hwndOwner
    CSIDL_PROGRAM_FILES, // nFolder
    0,                   // hToken
    SHGFP_TYPE_CURRENT,  // dwFlags
    path);               // pszPath
  if (hr == S_OK)
    printf("Program files at\r\n%s", path);
  else
    printf("failed to get folder");
}
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号