PathUnExpandEnvStrings (shlwapi)
Last changed: -202.74.138.1

.
Summary
Takes a fully qualified path, and replaces folder names with their associated environment strings.

C# Signature:

[DllImport("shlwapi.dll", CharSet=CharSet.Auto)]
static extern bool PathUnExpandEnvStrings(string pszPath, [Out] StringBuilder pszBuf, int cchBuf);

VB.NET Signature:

<System.Runtime.InteropServices.DllImport("shlwapi.dll", CharSet:=System.Runtime.InteropServices.CharSet.Auto)> _
   Shared Function PathUnExpandEnvStrings(ByVal pszPath As String, ByVal lpszPath As System.Text.StringBuilder, ByVal dx As Integer) As Boolean
End Function

Notes:

This is basically the inverse of ExpandEnvironmentStrings or Environment.ExpandEnvironmentVariables. Only Microsoft knows why this inverse function didn't make it's way into the framework.

Tips & Tricks:

Please add some!

Sample Code C#:

StringBuilder sb = new StringBuilder(MAX_PATH-1);
bool b = PathUnExpandEnvStrings(@"C:\Program Files\Test", sb, sb.Capacity);
// Result: b == true && sb.ToString() == @"%ProgramFiles%\Test"

Sample Code VB.NET:

Dim sb As New System.Text.StringBuilder(1024)
Dim blnOK As Boolean = PathUnExpandEnvStrings("C:\Program Files\Test", sb, sb.Capacity)
Dim strUnExpandEnvStrings As String

If blnOK = True Then strUnExpandEnvStrings = sb.ToString ' Should be %ProgramFiles%\Test on English OS

Alternative Managed API:

Do you know one? Please contribute it!

Documentation