Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I am using the following command to set a value to the environmental variable in a c# Console application.

 System.Environment.SetEnvironmentVariable(envvar, result,EnvironmentVariableTarget.Process);

After running the application in the command window, when I try to echo that variable ,I cannot see the value. I have to use this application in a batch file. I want the functionality like SET command. Please help..

Edit: I tried using System.Environment.SetEnvironmentVariable(envvar,result,EnvironmentVariableTarget.user) and to propagate the change I tried this Propagating Change in Env VAr. But I cant echo the variable in same command window.

Let me rephrase the question: I want to set a value to a Env Var in c#. I must be able to use that variable in same command window (ie i should not open a new cmd window to see the change). We use SET command and we can use that variable immediately .. rt ? I want such functionality. Plzz help

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
209 views
Welcome To Ask or Share your Answers For Others

1 Answer

When you use EnvironmentVariableTarget.Process the variable set will only visible in the current process as you can see in this sample:

System.Environment.SetEnvironmentVariable("myVar", "myValue", EnvironmentVariableTarget.Process);
string s = System.Environment.GetEnvironmentVariable("myVar",EnvironmentVariableTarget.Process);

Above myVar will show s = "myValue" but not visible in command window.

If you want to set the value visible at command windows then you need to use EnvironmentVariableTarget.User:

System.Environment.SetEnvironmentVariable("myVar", "myValue", EnvironmentVariableTarget.User);

This way the setting myVar=myValue will be stored and then you can see on command windows.

A detailed sample is located here


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...