views:

285

answers:

2

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?

+6  A: 

Use the SHGetFolderPath Windows API function and request CSIDL_MYDOCUMENTS.

James McNellis
i think that link not correct, fix: http://msdn.microsoft.com/en-us/library/bb762181%28VS.85%29.aspx
uray
Thanks - I've tried that, and something's not quite working - would you mind having a look at my edit in the question?
Smashery
+8  A: 

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.

Edit: You want to use CSIDL_PERSONAL, not CSIDL_MYDOCUMENTS. Demo code that works, at least on my machine:

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

#pragma comment(lib, "shell32.lib")

int main() { 
    CHAR my_documents[MAX_PATH];
    HRESULT result = SHGetFolderPath(NULL, CSIDL_PERSONAL, NULL, SHGFP_TYPE_CURRENT, my_documents);

    if (result != S_OK)
        std::cout << "Error: " << result << "\n";
    else
        std::cout << "Path: " << my_documents << "\n";
    return 0;
}
Jerry Coffin
Thanks - I've tried SHGetFolderPath, and something's not quite working - would you mind having a look at my edit in the question?
Smashery
Thank you very much!
Smashery