Skip to content

[Continued] Use SHGetKnownFolderPath to get path to localappdata for current user #5201

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 4 commits into
base: main
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
36 changes: 14 additions & 22 deletions Sources/CoreFoundation/CFKnownLocations.c
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@

#if TARGET_OS_WIN32
#include <userenv.h>
#include <shlobj_core.h>
#endif

CFURLRef _Nullable _CFKnownLocationCreatePreferencesURLForUser(CFKnownLocationUser user, CFStringRef _Nullable username) {
Expand Down Expand Up @@ -96,30 +97,21 @@ CFURLRef _Nullable _CFKnownLocationCreatePreferencesURLForUser(CFKnownLocationUs
}
case _kCFKnownLocationUserCurrent:
username = CFGetUserName();
// fallthrough
// The above API returns a non-NULL CFStringRef. The failed result is an empty string.
// We need to check for that case and fall through to the next case.
if (!CFEqual(username, CFSTR(""))) {
break;
}
// fallthrough.
case _kCFKnownLocationUserByName: {
DWORD size = 0;
GetProfilesDirectoryW(NULL, &size);

wchar_t* path = (wchar_t*)malloc(size * sizeof(wchar_t));
GetProfilesDirectoryW(path, &size);

CFStringRef pathRef = CFStringCreateWithCharacters(kCFAllocatorSystemDefault, path, size - 1);
free(path);

CFURLRef profilesDir = CFURLCreateWithFileSystemPath(kCFAllocatorSystemDefault, pathRef, kCFURLWindowsPathStyle, true);
CFRelease(pathRef);

CFURLRef usernameDir = CFURLCreateCopyAppendingPathComponent(kCFAllocatorSystemDefault, profilesDir, username, true);
CFURLRef appdataDir = CFURLCreateCopyAppendingPathComponent(kCFAllocatorSystemDefault, usernameDir, CFSTR("AppData"), true);
location = CFURLCreateCopyAppendingPathComponent(kCFAllocatorSystemDefault, appdataDir, CFSTR("Local"), true);
CFRelease(usernameDir);
CFRelease(appdataDir);
wchar_t* path = NULL;
SHGetKnownFolderPath(&FOLDERID_LocalAppData, 0, NULL, &path);

CFStringRef userPath = CFStringCreateWithCharacters(kCFAllocatorSystemDefault, path, wcslen(path));
CoTaskMemFree(path);

CFRelease(profilesDir);
if (user == _kCFKnownLocationUserCurrent) {
CFRelease(username);
}
location = CFURLCreateWithFileSystemPath(kCFAllocatorSystemDefault, userPath, kCFURLWindowsPathStyle, true);
CFRelease(userPath);
break;
}
}
Expand Down