开发者

ExpandEnvironmentStrings Not Expanding My Variables

I have a process under the Run key in the registry. It is trying to acc开发者_开发问答ess 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?


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));


I don't see any error checking code in your snippet, you don't assert the return value. If there's a problem, you'd never discover it. Also, you are using ANSI strings, beware of the weirdo requirement for the nSize argument (1 extra).


What about buffersize ? Is it initialized - to the right value ?

The documentation states that If the destination buffer is too small to hold the expanded string, the return value is the required buffer size, in characters.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜