From Visual C++, how do I get the path to the current user's My Documents folder?
Edit:
I have this:
TCHAR my_documents[MAX_PATH];
HRESULT result = SHGetFolderPath(NULL, CSIDL_MYDOCUMENTS, NULL, SHGFP_TYPE_CURRENT, my_documents);
However, result
is coming back with a value of E_INVALIDARG
. Any thoughts as to why this might be?
It depends on how old of a system you need compatibility with. For old systems, there's SHGetSpecialFolderPath. For somewhat newer systems, there's SHGetFolderPath. Starting with Vista, there's SHGetKnownFolderPath.
Here's some demo code that works, at least on my machine:
Use the
SHGetFolderPath
Windows API function and requestCSIDL_MYDOCUMENTS
.Using Visual Studio 2017 with an MFC application under Windows 10 I am using the following code snippet with SHGetKnownFolderPath function to get the current user's Documents folder:
Note that the documentation has this to say about the path variable usage and the path returned:
For a list of the
FOLDERID_
arguments possible see the MSDN article KNOWN_FOLDER_FLAG enumeration.how about this solution? Its working fine for me.
Note that CSIDL_PERSONAL will not return the desired folder if the user has changed the default save folder in the Win7 Documents library. To get the right folder, you need to use
SHLoadLibraryFromKnownFolder
to obtain theIShellLibrary
for the Documents library, useIShellLibrary::GetDefaultSaveFolder
to get theIShellItem
for the library's default save folder, and finally useIShellItem::GetDisplayName
to get the folder name.