Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use the MSBuild command line parameter called Configuration as a conditional compilation symbol?

I would like to display a string that tells user which build configuration was used to build the application. For example:

If the command line resembled this:

msbuild project.sln /t:Build /p:Configuration=Release

And then in the source code, I would like to do this:

Console.Writeline("You are running the " + <get the /p:Configuration value> + " version" );

The user would see this:

You are running the Release version

I know that we can declare conditional compilation symbols (#defines) at the command prompt such as how it is defined in this article and this one. But I want to use the existing variable called Configuration.

like image 473
101010 Avatar asked Oct 05 '22 13:10

101010


1 Answers

There are no way to do this, except as you said = using #if. MSBuild configuration name is just a name for set of configurations in project file to build specific flavor of your project. By default you do not have access to this configuration name from your code.

I see two ways how you can change the string in your code:

a) As you said - you can specify the conditional compilation symbols, so you can do something like

#if DEBUG
const string Flavor = "Debug";
#else
const string Flavor = "Release";
#endif
...
Console.WriteLine("You are running the " + Flavor + " version" );

b) You can play with your project file and include different set of files depending on the Configuration. If you will unload your project and open csproj as just a file - you will see for example

<ItemGroup>
  <Compile Include="MyApp.cs" />
</ItemGroup>

You can change to something like:

<ItemGroup>
  <Compile Include="MyApp.Release.cs" Condition="'$(Configuration)'=='Release'" />
  <Compile Include="MyApp.Debug.cs" Condition="'$(Configuration)'=='Debug'" />
</ItemGroup>

So this is how you will include different set of files for each configuration, where you can specify what configuration user has right now.

like image 184
outcoldman Avatar answered Oct 10 '22 03:10

outcoldman