vish1990
vish1990

Reputation: 384

Passing value from a C# program into a Windows environment variable

I have a C# program that calculates a date. I want to set an environment variable datayyyymmdd to be read outside the program to be expaned into a filename that I need to look for with the Dos code.

Can someone please help me with c# code sample or any link .

Thanks

Upvotes: 0

Views: 999

Answers (2)

Aacini
Aacini

Reputation: 67216

Modify your C# program so it just display in the screen the value of the variable instead of set the variable itself. Then, execute the .exe from the Batch file this way:

for /F "delims=" %%a in ('abc.exe "any parameter"') do set datayyyymmdd=%%a

Upvotes: 0

Mofi
Mofi

Reputation: 49086

This is not a trivial task as each process has its own environment variables table, especially if the environment variable should not be set permanently for all running processes.

The solution is quite simple.

In your C# application create a batch file with the line:

set YourVar=datayyyymmdd

The C# application could create this batch file with name "SetYourVar.bat" in directory for temporary files. The path of the temporary files directory can be get within the C# application from environment variable TEMP.

Your batch file contains the lines:

@echo off
"Full\Name\Of\C#\ConsoleApplication.exe" "parameters for this application"
if exist "%TEMP%\SetYourVar.bat" (
   call "%TEMP%\SetYourVar.bat"
   del "%TEMP%\SetYourVar.bat" >nul
)
"Full\Name\Of\Other\DOS\Application.exe"

So instead of trying to set the environment variables to use in other applications directly within the C# console application, write the lines to set them into a batch file called next by the batch file which started the C# console application and next deletes this temporary batch file just used to set environment variables.

Upvotes: 1

Related Questions