How to get user home directory on Windows?

≯℡__Kan透↙ 提交于 2020-01-23 01:05:40

问题


I'm developing a cross-platform library that is meant to load configuration files from a user's home directory. The idea is to automatically provide configuration parameters without editing code.

This library can be used in desktop apps or in daemons/services. In (I assume) most Unix environments I can use getpwuid() to get the home directory of the user. In Windows SO told me I could use SHGetKnownFolderPath but its documentation says its for desktop apps only. Is there a way to get this path, on Windows, for the user running a service?


回答1:


For a console application the simplest method is to either retrieve the USERPROFILE environment variable or concatenate the values of the HOMEDRIVE and HOMEPATH environment variables.

Use the getenv() function in the standard library: https://msdn.microsoft.com/en-us/library/tehxacec.aspx

Example program:

#include <stdlib.h>
#include <stdio.h>

int main(int argc, char** argv) {
    printf("USERPROFILE = %s\n", getenv("USERPROFILE"));
    printf("HOMEDRIVE   = %s\n", getenv("HOMEDRIVE"));
    printf("HOMEPATH    = %s\n", getenv("HOMEPATH"));
    return 0;
}

Output:

USERPROFILE = C:\Users\myuser
HOMEDRIVE   = C:
HOMEPATH    = \Users\myuser



回答2:


You could resolve %HOMEPATH% using ExpandEnvironmentStrings(...)




回答3:


What about this:

#include <shlobj.h> 

WCHAR profilePath[MAX_PATH];
HRESULT result = SHGetFolderPathW(NULL, CSIDL_PROFILE, NULL, 0, profilePath);
if (SUCCEEDED(result)) {
    // Do whatever you want with it
    // For example:
    // QString::fromWCharArray(profilePath)
}

I haven't tested it, though.

Note that what you receive is a wchar array (necessary to handle paths with special characters).

I think it's also possible to query special folders of other users than the current one by using the hToken parameter.

Also refer to the documentation: https://msdn.microsoft.com/en-us/library/windows/desktop/bb762181(v=vs.85).aspx

I used this code in another case where I wanted to obtain the start menu location. See this answer: C++: How do I create a Shortcut in the Start Menu on Windows




回答4:


So do you want to get user home directory in service state? - If you want that in service state, you have to use GetUserToken() to get user token then duplicate them for CreateprocessAsUser() - Else I think it's better using SHGetSpecialPath(), SHGetTempPath().



来源:https://stackoverflow.com/questions/42696260/how-to-get-user-home-directory-on-windows

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!