ExpandEnvironmentStrings Not Expanding My Variables

c++, environment-variables, winapi

Solution

One problem is that you are providing the wrong parameters to `ExpandEnvironmentStrings` and then using a cast to hide that fact (although you do need a cast to get the correct type out of a `CString`).

You are also using the wrong value for the last parameter. That should be the size of the output buffer, not the size of the input length (from the documentation `the maximum number of characters that can be stored in the buffer pointed to by the lpDst parameter`)

Putting that altogether, you want:

ExpandEnvironmentStrings((LPCTSTR)strPath,
                         cOutputPath,
                         sizeof(cOuputPath) / sizeof(*cOutputPath));

Problem

I have a process under the Run key in the registry. It is trying to access an environment variable that I have defined in a previous session. I'm using ExpandEnvironmentStrings to expand the variable within a path. The environment variable is a user profile variable. When I run my process on the command line it does not expand as well. If I call 'set' I can see the variable. Some code... ``` CString strPath = "\\\\server\\%share%" TCHAR cOutputPath[32000]; DWORD result = ExpandEnvironmentStrings((LPSTR)&strPath, (LPSTR)&cOutputPath, _tcslen(strPath) + 1); if ( !result ) { int lastError = GetLastError(); pLog->Log(_T( "Failed to expand environment strings. GetLastError=%d"),1, lastError); } ``` When debugging Output path is exactly the same as Path. No error code is returned. What is goin on?

Original source