August 26, 2009

How To: Get the Content of Certain Environment Variable, ie: %ProgramFiles%

Code Snippet

#include <windows.h>
#include <string>

using namespace std;

wstring GetContentFromEnvironmentVariable(const wstring& wstrVariable)
{
  // Get the content of %ProgramFiles%

  wstring wstrRtn;
  DWORD dwSize = ::GetEnvironmentVariableW(wstrVariable.c_str(), NULL, NULL);
  if(dwSize > 0)
  {
    wchar_t* wszContent = new wchar_t [dwSize];
    dwSize = ::GetEnvironmentVariableW(wstrVariable.c_str(), wszContent, dwSize);

    wstrRtn = wszContent;

    delete [] wszContent;
    wszContent = NULL;
 }

 return wstrRtn;
}

Reference on MSDN
GetEnvironmentVariable Function