How to get the %AppData% folder in C?

旧时模样 提交于 2019-11-28 12:13:24

Use SHGetSpecialFolderPath with a CSIDL set to the desired folder (probably CSIDL_APPDATA or CSIDL_LOCAL_APPDATA).

You can also use the newer SHGetFolderPath() and SHGetKnownFolderPath() functions. There's also SHGetKnownFolderIDList() and if you like COM there's IKnownFolder::GetPath().

If I recall correctly it should just be

#include <stdlib.h>
getenv("APPDATA");

Edit: Just double-checked, works fine!

Using the %APPDATA% environment variable will probably work most of the time. However, if you want to do this the official Windows way, you should use use the SHGetFolderPath function, passing the CSIDL value CSIDL_APPDATA or CSIDL_LOCAL_APPDATA, depending on your needs.

This is what the Environment.GetFolderPath() method is using in .NET.

EDIT: Joey correctly points out that this has been replaced by SHGetKnownFolderPath in Windows Vista. News to me :-).

You might use these functions:

#include <stdlib.h>
char *getenv( 
   const char *varname 
);
wchar_t *_wgetenv( 
   const wchar_t *varname 
);

Like so:

#include <stdio.h>
char *appData = getenv("AppData");
printf("%s\n", appData);

Sample code:

TCHAR szPath[MAX_PATH];
if (SUCCEEDED(SHGetFolderPath(NULL,
   CSIDL_APPDATA | CSIDL_FLAG_CREATE,
   NULL,
   0,
   szPath)))
{
   PathAppend(szPath, TEXT("MySettings.xml"));
   HANDLE hFile = CreateFile(szPath, ...);
}

CSIDL_APPDATA = username\Application Data. In Window 10 is: username\AppData\Roaming

CSIDL_FLAG_CREATE = combine with CSIDL_ value to force folder creation in SHGetFolderPath()

You can also use:

CSIDL_LOCAL_APPDATA = username\Local Settings\Application Data (non roaming)

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