babyjys
babyjys

Reputation: 1

c++ How to path LocalAppData folder

I need to find the path of this file:

("C:\\Users\\*username*\\AppData\\Local")

I tried everything but I couldn't because of the username

If anyone knows, can they explain how I should get the LocalAppData path?

Upvotes: 0

Views: 1509

Answers (2)

CherryDT
CherryDT

Reputation: 29072

The recommended way1 to do this is to call SHGetKnownFolderPath with FOLDERID_LocalAppData:

#include <Windows.h>
#include <iostream>
#include <shlobj_core.h>
#include <KnownFolders.h>

int main() {
    PWSTR path = NULL;
    HRESULT hres = SHGetKnownFolderPath(FOLDERID_LocalAppData, 0, NULL, &path);
    if (SUCCEEDED(hres)) {
        std::wcout << path << std::endl;
        CoTaskMemFree(path);
    }
    return 0;
}

There is also an environment variable LOCALAPPDATA that you could use, but it's not guaranteed to contain the expected value since it can be modified by the parent process.


1: Available since Windows Vista. There is an older function SHGetFolderPath in case compatibility with Windows 2000/XP is required.

Upvotes: 2

Klayser
Klayser

Reputation: 344

You can use SHGetFolderPath() (for maximum compatibility).

You have to specify the CSIDL value for the folder you want, in your case that would be CSIDL_LOCAL_APPDATA.

After Windows Vista, you can instead use SHGetKnowFolderPath(), which requires a folder KNOWFOLDERID, in your case this would be FOLDERID_LocalAppData.

To use this, you have to include <shlobj.h>

Upvotes: 2

Related Questions