The Wiert Corner – irregular stream of stuff

Jeroen W. Pluimers on .NET, C#, Delphi, databases, and personal interests

  • My badges

  • Twitter Updates

  • My Flickr Stream

  • Pages

  • All categories

  • Enter your email address to subscribe to this blog and receive notifications of new posts by email.

    Join 1,860 other subscribers

.NET/C#: ExpandEnvironmentStrings equivalent is Environment.ExpandEnvironmentVariables; expands environment strings

Posted by jpluimers on 2012/08/09

A while ago, I needed a way to defer settings to environment variables in a .NET application written in C#.

The easiest way to do this is to keep the same syntax as for expanding environment variables in batch files: use the %ENVIRONMENTVARIABLE% syntax (not the delayed expansion !ENVIRNMENTVARIABLE! syntax).

The reason is that there is a Windows API function ExpandEnvironmentStrings that handles all the expansion magic.

Don’t P/Invoke that function yourself, as there is already a very nice Environment.ExpandEnvironmentVariables wrapper since the .NET framework 1.1 that handles all the gory details for you (like marshalling the strings, making sure that lpDst contains enough space for the expansion).

–jeroen

Leave a comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.