I am trying to set environment variables using project file (ex. .vcxproj)
I looked at property functions but it didn't seem to have such function.
I know there is a way to retrieve environment variable but couldn't find how to set it.
I feel like there should be way to set environment variables in project file.
Windows Environment Variables Do so by pressing the Windows and R key on your keyboard at the same time. Type sysdm. cpl into the input field and hit Enter or press Ok. In the new window that opens, click on the Advanced tab and afterwards on the Environment Variables button in the bottom right of the window.
MSBuild lets you set properties on the command line by using the -property (or -p) switch. These global property values override property values that are set in the project file. This includes environment properties, but does not include reserved properties, which cannot be changed.
In Visual Studio 2019 right-click your project, choose Properties . In the project properties window, select the Debug tab. Then, under Environment variables change the value of your environment from Development to Production or other environments.
The coded task can be put right at the project file since MSBuild v4.0. Like this:
<UsingTask TaskName="SetEnvironmentVariableTask" TaskFactory="CodeTaskFactory" AssemblyFile="$(MSBuildToolsPath)\Microsoft.Build.Tasks.v$(MSBuildToolsVersion).dll"> <ParameterGroup> <Name ParameterType="System.String" Required="true" /> <Value ParameterType="System.String" Required="true" /> </ParameterGroup> <Task> <Using Namespace="System" /> <Code Type="Fragment" Language="cs"> <![CDATA[ Environment.SetEnvironmentVariable(Name, Value); ]]> </Code> </Task> </UsingTask>
Note that in MSBuild 14+, the AssemblyFile reference should be just:
AssemblyFile="$(MSBuildToolsPath)\Microsoft.Build.Tasks.Core.dll"
The SetEnvironmentVariableTask
can be then used from the target:
<Target Name="SampleTarget" BeforeTargets="Build"> <SetEnvironmentVariableTask Name="TEST_ENV_VAR" Value="$(MSBuildProjectName)" /> </Target>
That's much handier than authoring a separate .DLL for small MSBuild task(s).
A couple of things:
If you are only using the variable in the context of MSBuild, then you can just use the standard MSBuild variables instead of trying to set an environment variable
If do need to set an env var, well, it's not an out-of-box thing. You need to write a custom task and then leverage it in the project file. Here's a link to an MSDN thread that outlines how to do this.
How to set envrionment variables in MSBuild file?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With