Save environment variables after exiting the application

Is it possible to save the environment variable in a console application, which is available after the process exits.

I want the console application to set the line available for the batch file that executed it.

The console application is in dotnet.

+3
source share
4 answers

You can use Environment.SetEnvironmentVariable :

Environment.SetEnvironmentVariable("SomeVariable", "Some value", EnvironmentVariableTarget.User);

The last parameter defines the scope and lifetime of the variable (process, user or machine). If you want to set a variable for the machine, you will need to run it as admin.

: , , ( , , , , ).

2: , , , . , , , .net- . script , :

. :

static void Main(string[] args)
{
    string outputFile = @"c:\temp\setvars.bat";
    string variable = "set SomeVariable=Some value";
    File.WriteAllText(outputFile, variable);
}

BAT :

call myconsoleapp.exe
call c:\temp\setvars.bat
echo %SomeVariable%
+5

Xiaofu, , , . , , :

for /f "tokens=1,2 delims=," %%a in ('MyProgram.exe') do (
    set %%a=%%b
    set %%a=%%b
)

, , for.

+4

, , , , .

Environment.SetEnvironmentVariable EnvironmentVariableTarget . - % my_var%.

Environment.SetEnvironmentVariable("my_var", "data", EnvironmentVariableTarget.User);

: , , . , # , , . :

for /f "tokens=1,2 delims=," %%a in (data.txt) do (
if %%a==env1 echo %%b
if %%a==env2 echo %%b
)

... where data.txt might look like this:

env1,hello
env2,there
+3
source

Yes, set the system environment variable instead of the process environment variable. (I think that technically the User evironment variable will also persist, but only for user contexts).

Use the system.environment class to go to the SetEnvironmentVariable method.

0
source

Source: https://habr.com/ru/post/1709358/


All Articles