How to obtain the path to OneDrive?

Hi,

I know I can obtain the path to OneDrive in the command line like this:

 
c:\>echo %ONEDRIVE%


and the system will show the path, something like this:

 
C:\Users\Owner\OneDrive


But how can I obtain that path in a string in a C++ program??


Regards,
Juan
1
2
3
4
5
6
7
8
9
10
11
#include <iostream>
#include <cstdlib>

int main()
{
    // https://en.cppreference.com/w/cpp/utility/program/getenv
    const char* const one_drive_path = std::getenv( "ONEDRIVE" ) ;

    if(one_drive_path) std::cout << one_drive_path << '\n';
    else std::cout << "could not determine one_drive_path\n" ;
}

Thanks!!
If you don't want to rely on environment variables, read from the registry:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
static std::wstring GetOneDrivePath(void)
{
    // Try open registry key
    HKEY hKey = NULL;
    if (RegOpenKeyW(HKEY_CURRENT_USER, L"Software\\Microsoft\\OneDrive\\Accounts\\Personal", &hKey) != ERROR_SUCCESS)
    {
        return std::wstring();
    }

    // Buffer to store string read from registry
    wchar_t value[1024U];
    DWORD type = 0U, length = _countof(value);

    // Query string value
    if (RegQueryValueExW(hKey, L"UserFolder", NULL, &type, reinterpret_cast<LPBYTE>(&value), &length) != ERROR_SUCCESS)
    {
        goto failure;
    }

    // Create a std::string from the value buffer
    if ((type == REG_SZ) || (type == REG_EXPAND_SZ) || (type == REG_MULTI_SZ))
    {
        RegCloseKey(hKey);
        return std::wstring(value);
    }

failure:
    RegCloseKey(hKey);
    return std::wstring();
}

int main()
{
    std::wcout << L"OneDrive folder: \"" << GetOneDrivePath() << L'"' << std::endl;
}
Last edited on
Topic archived. No new replies allowed.