30

I looked all over the internet and there doesn't seem to be a decent solution that I could find. I want to be able to programmatically in C++ obtain the path "%ALLUSERSPROFILE%\Application Data" that explorer can translate into a real path.

Can I do this without relying on third-party code?

Brian T Hannan
  • 3,925
  • 18
  • 56
  • 96

3 Answers3

52

Use SHGetFolderPath with CSIDL_COMMON_APPDATA as the CSIDL.

TCHAR szPath[MAX_PATH];
if (SUCCEEDED(SHGetFolderPath(NULL, CSIDL_COMMON_APPDATA, NULL, 0, szPath)))
{
    //....
}
interjay
  • 107,303
  • 21
  • 270
  • 254
21

Just to suppliment interjay's answer

  1. I had to include shlobj.h to use SHGetFolderPath.

  2. Often you may need to read a file from appdata, to do this you need to use the pathAppend function (shlwapi.h is needed for this).

#include <shlwapi.h>
#pragma comment(lib,"shlwapi.lib")
#include "shlobj.h"

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 ) ) )
{
    // Append product-specific path
    PathAppend( szPath, _T("\\My Company\\My Product\\1.0\\") );
}

See here for more details.

Sam
  • 7,252
  • 16
  • 46
  • 65
Danield
  • 121,619
  • 37
  • 226
  • 255
  • 1
    +1 and a note: to use _T("...") you have to `#include ` – jyz Aug 11 '13 at 20:46
  • 2
    You should be using the `TEXT()` macro instead of the `_T()` macro (or, stop using `TCHAR` altogether - unless you really need to support Win9x/ME). `TEXT()` is used by the Win32 API, `_T()` is used by the C runtime library. – Remy Lebeau Aug 25 '14 at 22:49
-4

you can also read the value from the registry

path = HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\Shell Folders

key = Common AppData

Remus Rigo
  • 1,454
  • 8
  • 34
  • 60
  • 11
    Undocumented and subject to change; avoid it. There's the API, use it. – Matteo Italia May 24 '10 at 20:00
  • 4
    Note that 'Subject to change' status is subject to change for all things in Win32 world. – ActiveTrayPrntrTagDataStrDrvr Nov 13 '12 at 09:10
  • The API is not always available. Certain very early versions of Windows not running desktops do not have the SHGetFolderPath API. But, if you do not have to support Windows XP or Windows 2000, you can rely on SHGetFolderPath's availability. Yes, obscure, perhaps an edge case, but enough people have run into this to influence at least one boost library to use this approach. – Joseph Van Riper Mar 14 '19 at 11:18