Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 233
Steve Johnson Avatar asked Nov 07 '12 17:11

Steve Johnson


People also ask

How does Setenv work in C?

DESCRIPTION. The setenv() function shall update or add a variable in the environment of the calling process. The envname argument points to a string containing the name of an environment variable to be added or altered. The environment variable shall be set to the value to which envval points.

What is an environment variable in C?

Environment variable is a global variable that can affect the way the running process will behave on the system.

Which command can be used to remove an environmental variable?

The dsadmin command can be used for deleting an environment variable in a particular project.


2 Answers

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`](http://msdn.microsoft.com/en-us/library/system.environment.expandenvironmentvariables.aspx):
var expanded = Environment.ExpandEnvironmentVariables(
    "This is my %WINDIR% in %SYSTEMROOT%, and temp is %TEMP%")
like image 104
lc. Avatar answered Oct 11 '22 01:10

lc.


Environment.ExpandEnvironmentVariables("%windir%\SomeFolder")
like image 21
Jason Avatar answered Oct 11 '22 01:10

Jason