如何使用 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
How do I get the application data path in Windows using C++?
提问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 SHGetFolderPath
with CSIDL_COMMON_APPDATA
as the CSIDL.
使用SHGetFolderPath
与CSIDL_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 的回答
I had to include
shlobj.h
to useSHGetFolderPath
.Often you may need to read a file from appdata, to do this you need to use the
pathAppend
function (shlwapi.h
is needed for this).
我必须包含
shlobj.h
才能使用SHGetFolderPath
.通常,您可能需要从 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
键 =通用应用数据