简体   繁体   中英

environmental variable in a c#

I am using the following command to set a value to the environmental variable in ac# 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

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

In order to see the env in the current batch process. You have to output it in you program as string and parse it and call set in the batch file.

Or you can try EnvironmentVariableTarget.User. The env will be visible in all new processes when setted with this option.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM