如何使用 C++ 在 Windows 中获取应用程序数据路径?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2899013/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-28 11:26:09  来源:igfitidea点击:

How do I get the application data path in Windows using C++?

c++windowsapplication-data

提问by Brian T Hannan

I looked all over the internet and there doesn't seem to be a decent solution that I could find. I want to be able to programmatically in C++ obtain the path "%ALLUSERSPROFILE%\Application Data" that explorer can translate into a real path.

我查看了整个互联网,似乎没有找到合适的解决方案。我希望能够在 C++ 中以编程方式获取资源管理器可以转换为真实路径的路径“%ALLUSERSPROFILE%\Application Data”。

Can I do this without relying on third-party code?

我可以在不依赖第三方代码的情况下做到这一点吗?

回答by interjay

Use SHGetFolderPathwith CSIDL_COMMON_APPDATAas the CSIDL.

使用SHGetFolderPathCSIDL_COMMON_APPDATA作为CSIDL。

TCHAR szPath[MAX_PATH];
if (SUCCEEDED(SHGetFolderPath(NULL, CSIDL_COMMON_APPDATA, NULL, 0, szPath)))
{
    //....
}

回答by Danield

Just to suppliment interjay's answer

只是为了补充 interjay 的回答

  1. I had to include shlobj.hto use SHGetFolderPath.

  2. Often you may need to read a file from appdata, to do this you need to use the pathAppendfunction (shlwapi.his needed for this).

  1. 我必须包含shlobj.h才能使用SHGetFolderPath.

  2. 通常,您可能需要从 appdata 读取文件,为此您需要使用该pathAppend函数(shlwapi.h为此需要)。

#include <shlwapi.h>
#pragma comment(lib,"shlwapi.lib")
#include "shlobj.h"

TCHAR szPath[MAX_PATH];
// Get path for each computer, non-user specific and non-roaming data.
if ( SUCCEEDED( SHGetFolderPath( NULL, CSIDL_COMMON_APPDATA, NULL, 0, szPath ) ) )
{
    // Append product-specific path
    PathAppend( szPath, _T("\My Company\My Product\1.0\") );
}

See herefor more details.

请参阅此处了解更多详情。

回答by Remus Rigo

you can also read the value from the registry

您还可以从注册表中读取值

path = HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\Shell Folders

路径 = HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\Shell Folders

key = Common AppData

键 =通用应用数据