Getting user temporary folder path in Windows

后端 未结 9 1636
醉梦人生
醉梦人生 2020-12-30 00:45

How I can get the user\'s temp folder path in C++? My program has to run on Windows Vista and XP and they have different temp paths. How I can get it without losing compatib

9条回答
  •  余生分开走
    2020-12-30 01:24

    In Windows 10, this can be tricky because the value of the Temporary Path depends not only what it's set to by default, but also what kind of app you're using. So it depends what specifically you need.

    [Common Area] TEMP in User's Local App Data

    #include 
    #include 
    #include 
    #include 
    // ...
    static void GetUserLocalTempPath(std::wstring& input_parameter) {
        static constexpr std::wstring_view temp_label = L"\\Temp\\";
        HWND folder_handle = { 0 };
        WCHAR temp_path[MAX_PATH];
        auto get_folder = SHGetFolderPath( 
            folder_handle, CSIDL_LOCAL_APPDATA, NULL, SHGFP_TYPE_DEFAULT, temp_path
        );
        if (get_folder == S_OK) {
            input_parameter = static_cast(temp_path);
            input_parameter.append(temp_label);
            CloseHandle(folder_handle);
        }
    }
    

    GetUserLocalTempPath will likely return the full name instead of the short name.
    Also, if whatever is running it is doing it as as SYSTEM instead of a logged in user, instead of it returning %USERPROFILE%\AppData\Local\Temp, it will return something more like, C:\Windows\System32\config\systemprofile\AppData\Local\Temp

    Temp for whatever the TEMP environment variable is

    #include 
    // ...
    static void GetEnvTempPath(std::wstring& input_parameter) {
        wchar_t * env_var_buffer = nullptr;
        std::size_t size = 0;
        if ( _wdupenv_s(&env_var_buffer, &size, L"TEMP") == 0 &&
             env_var_buffer != nullptr) {
            input_parameter = static_cast(env_var_buffer);
        }
    }
    

    [Robust] Temp for whatever is accessible by your app (C++17)

    #include 
    // ...
    auto temp_path = std::filesystem::temp_directory_path().wstring();
    

    temp_directory_path will likely return the short name instead of the full name.


    You're probably going to get the most use out of the first and last functions depending on your needs. If you're dealing with AppContainer apps, go for the last one provided by . It should return something like,

    C:\Users\user name\AppData\Local\Packages\{APP's GUID}\AC\Temp

提交回复
热议问题