Win32 function to get path to C:\ProgramData

Mike2012 picture Mike2012 · Jun 25, 2012 · Viewed 24.5k times · Source

My app needs to install some files that can be edited by the application at run time. Install shield provides an alias [CommonAppDataFolder] that will resolve to c:\programData on Vista and Windows 7 and will also work on Windows XP. Is there a win32 function that will return a similar path?

Maybe I need to call different functions depending on the operating system?

Answer

Roman R. picture Roman R. · Jun 25, 2012

SHGetFolderPath/SHGetSpecialFolderPath get you that, with CSIDL_COMMON_APPDATA argument.

See code snippet here (at the bottom): How to write a Windows XP Application that stores user and application data in the correct location by using Visual C++ ; the original link is no longer valid - code snippet is pulled below):

include <shlwapi.h>
#pragma comment(lib,"shlwapi.lib")
void CreateTemporaryFile()
{
   TCHAR szPath[MAX_PATH];
   // Get path for each computer, non-user specific and non-roaming data.
   if ( SUCCEEDED( SHGetFolderPath( NULL, CSIDL_COMMON_APPDATA, 
                                    NULL, 0, szPath ) ) )
   {
      TCHAR szTempFileName[MAX_PATH];
      // Append product-specific path - this path needs to already exist
      // for GetTempFileName to succeed.
      PathAppend( szPath, _T("\\My Company\\My Product\\1.0\\") );
      // Generate a temporary file name within this folder.
      if (GetTempFileName( szPath, 
                           _T("PRE"),
                           0,
                           szTempFileName ) != 0 )
      {
         HANDLE hFile = NULL;
         // Open the file.
         if (( hFile = CreateFile( szTempFileName, 
                                   GENERIC_WRITE, 
                                   0, 
                                   NULL, 
                                   CREATE_ALWAYS, 
                                   FILE_ATTRIBUTE_NORMAL, 
                                   NULL )) != INVALID_HANDLE_VALUE )
         {
            // Write temporary data (code omitted).
            CloseHandle( hFile );
         }
      }
      else
          DWORD err = GetLastError();
   }
}
  • Windows XP: C:\Documents and Settings\All Users\Application Data
  • Windows Vista: C:\ProgramData
  • Windows 7: C:\ProgramData

See also: CSIDL.