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
Parameter | Type | Description |
---|---|---|
rfid |
REFKNOWNFOLDERID | Identifier of the known folder. Use constants such as FOLDERID_Documents . |
dwFlags |
DWORD | Flags that modify the path retrieval. Common values:
|
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
- The function works on Windows Vista and later. For pre‑Vista platforms use
SHGetFolderPath
. - When
KF_FLAG_CREATE
is specified, the folder is created if it does not already exist. - If the known folder is redirected (e.g., to a network location), the returned path reflects the current location.
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.