views:

255

answers:

3

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?

+1  A: 

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

Hans Passant
I updated to post to better reflect my code. And I did notice that strange requirement for the ANSI. The function does not return an error. :\ Just seems to do nothing at all!
Adam Driscoll
@Adam: that didn't help much. How are strPath and Path related? Why are you casting? Casting is bad.
Hans Passant
Sorry update the code. I was casting because the compiler was complaining...great idea right?
Adam Driscoll
+1  A: 

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.

RaphaelSP
+2  A: 

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));
R Samuel Klatchko
Right on the head. Thanks. I just need to take my time with this C++ business... .Net has made me lazy...
Adam Driscoll