SHGetFolderPath

Retrieves the path of a special folder.

Syntax


HRESULT SHGetFolderPath(
  [in, optional] HWND    hwndOwner,
  [in]           int     nFolder,
  [in, optional] HANDLE  hToken,
  [in]           DWORD   dwFlags,
  [out]          LPTSTR  pszPath
);
        

Parameters

Parameter Type Description
hwndOwner [in, optional] HWND A handle to the owner window of any dialog box that the function displays. This parameter can be NULL.
nFolder [in] int A value that specifies the folder to be retrieved. This parameter can be one of the CSIDL values.
hToken [in, optional] HANDLE A handle to a user token to use to make the call. This parameter must be NULL.
dwFlags [in] DWORD Flags that specify how the folder path is to be retrieved. See SHGFP_FLAG values for more information.
pszPath [out] LPTSTR A pointer to a buffer that receives the path of the folder. The buffer must be large enough to contain MAX_PATH characters.

Return Value

Returns S_OK if successful, or an error code otherwise.

Remarks

SHGetFolderPath is a generalized version of SHGetSpecialFolderPath. It allows for the retrieval of paths for a wider range of special folders.

Note: For new development, consider using SHGetKnownFolderPath and the KNOWNFOLDERID enumeration, which provides a more robust and extensible way to access known folders.

Example Code

C++ Example

#include <windows.h>
#include <shlobj.h>
#include <iostream>

int main() {
    TCHAR szPath[MAX_PATH];

    // Get the path to the user's Documents folder
    HRESULT hr = SHGetFolderPath(
        NULL,                  // No owner window
        CSIDL_PERSONAL,        // CSIDL for the personal folder (Documents)
        NULL,                  // No user token
        SHGFP_TYPE_CURRENT,    // Use current user settings
        szPath                 // Buffer to receive the path
    );

    if (SUCCEEDED(hr)) {
        std::wcout << L"Documents folder path: " << szPath << std::endl;
    } else {
        std::cerr << L"Failed to get Documents folder path. HRESULT: " << hr << std::endl;
    }

    return 0;
}
            

See Also