How to resolve environment variables programatically in C# without using Environment Enum?

Steve Johnson picture Steve Johnson · Nov 7, 2012 · Viewed 8k times · Source

Possible Duplicate:
Expand environment variable for My Documents

We often use %% delimited environment variables in Command prompt in Windows Xp, 7, Vista, Server 2003-2008R2 and possibly in future windows versions. Examples are:

%windir%
%systemroot%
%temp%

I need to be able to programatically resolve these environment variables using C#.

Please do not suggest Environmen.SpecialFolder , because i am getting values from a webservice in the above formats and i need to able to programmatically resolve them and determine physical location of these paths on server. My scenario is a class libarary project and i may NOT require/be able to use Server.MapPath

I am looking for a generic method builtin or custom that can help me resolve all environment variables pro grammatically and calculate local physical paths from these variables just Command Prompt or Windows Explorer or Run Command does !

I have seen questions similar to these on StackOverFlow but couldn't find any marked answers. Please note that Environment.Xxxxx Enum doesnt cater for the scenario i am working through.

Any help is appreciated. I am using .NET 4.0 Complete Framework Profile with C#.

Answer

lc. picture lc. · Nov 7, 2012

You can use System.IO.Path.GetFullPath. For example:

var resolvedPath = Path.GetFullPath("%WINDIR%");

Or if you just want to expand variables in a string, use Environment.ExpandEnvironmentVariables:

var expanded = ExpandEnvironmentVariables(
    "This is my %WINDIR% in %SYSTEMROOT%, and temp is %TEMP%")