5

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.

Community
  • 1
  • 1
101010
  • 14,866
  • 30
  • 95
  • 172

1 Answers1

4

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.

outcoldman
  • 11,584
  • 2
  • 26
  • 30
  • Side note, the compilation symbol DEBUG doesn't necessarily mean "Debug configuration"; the debug configuration typically sets this flag, but it's not forced to. – JerKimball Apr 03 '13 at 06:19
  • I liked your second solution. I have several (more than 2) configurations. Great idea! Thanks! – 101010 Apr 03 '13 at 13:09
  • is there a way to still get the Configuration-value in the C# code? – casaout Dec 19 '17 at 13:05