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

↘锁芯ラ 提交于 2019-12-10 16:25:22

问题


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


回答1:


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%")



回答2:


Environment.ExpandEnvironmentVariables("%windir%\SomeFolder")


来源:https://stackoverflow.com/questions/13275338/how-to-resolve-environment-variables-programatically-in-c-sharp-without-using-en

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!