MSDN Documentation – Windows API

SHGetKnownFolderPath

Retrieves the full path of a known folder identified by its KNOWNFOLDERID.

Header

#include <shlobj.h>

Library

Shell32.lib

Syntax

HRESULT SHGetKnownFolderPath(
    REFKNOWNFOLDERID rfid,
    DWORD            dwFlags,
    HANDLE           hToken,
    PWSTR            *ppszPath
);

Parameters

ParameterTypeDescription
rfid REFKNOWNFOLDERID Identifier of the known folder. Use constants such as FOLDERID_Documents.
dwFlags DWORD Flags that modify the path retrieval. Common values:
  • KF_FLAG_DEFAULT – default behavior
  • KF_FLAG_CREATE – create the folder if it does not exist
hToken HANDLE Access token for a user. Pass NULL to use the current user.
ppszPath PWSTR* Receives the address of a Unicode string that contains the folder path. The caller must free it with CoTaskMemFree.

Return Value

Returns S_OK on success. On failure, returns an HRESULT error code.

Remarks

Example

// Example: Retrieve the path to the Documents folder
#include <windows.h>
#include <shlobj.h>
#include <iostream>

int wmain()
{
    PWSTR path = nullptr;
    HRESULT hr = SHGetKnownFolderPath(FOLDERID_Documents, KF_FLAG_DEFAULT, nullptr, &path);
    if (SUCCEEDED(hr))
    {
        std::wcout << L"Documents folder: " << path << std::endl;
        CoTaskMemFree(path);
    }
    else
    {
        std::wcerr << L"Error: " << std::hex << hr << std::endl;
    }
    return 0;
}
Tip: Use IID_PPV_ARGS with SHGetKnownFolderPath when calling from COM-aware code.

Related Functions