How to obtain build configuration at runtime?
Asked Answered
G

8

31

Does anyone know how to get the current build configuration $(Configuration) in C# code?

Goings answered 6/5, 2009 at 12:13 Comment(0)
A
20

Update

Egors answer to this question ( here in this answer list) is the correct answer.

You can't, not really.
What you can do is define some "Conditional Compilation Symbols", if you look at the "Build" page of you project settings, you can set these there, so you can write #if statements to test them.

A DEBUG symbol is automatically injected (by default, this can be switched off) for debug builds.

So you can write code like this

#if DEBUG
        RunMyDEBUGRoutine();
#else
        RunMyRELEASERoutine();
#endif

However, don't do this unless you've good reason. An application that works with different behavior between debug and release builds is no good to anyone.

Adjoint answered 6/5, 2009 at 12:29 Comment(6)
It may help when developing Windows Services (no need to install / easier debugging)Melany
@Scoregraphic: However with quite different behavior (service vs. command line app)!!!Deedradeeds
Why is conditional expression not finding my custom configuration ? I have code like this: #if WCFDebug /*my code*/ #endif - but it simply doesn't find it. I've added configuration inside settings.Uuge
And what if you have DEV, TEST, QA, PREPROD, PROD ?Appellee
@Appellee Then define conditional compilation symbols for those as well in your project properties.Faison
@Appellee the above answer might have been true several years ago, but modern versions of .net let you get the info. See Egor Novikov's answer below.Manolete
I
37

There is AssemblyConfigurationAttribute in .NET. You can use it in order to get name of build configuration

var assemblyConfigurationAttribute = typeof(CLASS_NAME).Assembly.GetCustomAttribute<AssemblyConfigurationAttribute>();
var buildConfigurationName = assemblyConfigurationAttribute?.Configuration;
Incomplete answered 5/3, 2020 at 12:19 Comment(1)
I've edited my accepted answer and linked to this. Good find Egor :)Adjoint
R
22

If you unload your project (in the right click menu) and add this just before the </Project> tag it will save out a file that has your configuration in it. You could then read that back in for use in your code.

<Target Name="BeforeBuild">
    <WriteLinesToFile File="$(OutputPath)\env.config" 
                      Lines="$(Configuration)" Overwrite="true">
    </WriteLinesToFile>
</Target>
Redd answered 12/1, 2010 at 0:7 Comment(3)
I have used Vaccano's solution. I have to dynamically change some configuration basing on each build configuration, not just debug or release, and this solution works out great for me. Thanks.Preterition
I used this in common with a Wix# (WixSharp) installer program to have my C# console app "Release" build binary & config files fed to the Wix# installer, and it worked great for my needs! (Wix# is based on the Windows Installer XML tools for building MSI installers, wixtoolset.org, and Wix# allows you to write your installer in C# code that generates the WiX xml files, instead of "coding in XML". github.com/oleg-shilo/wixsharp/wiki/…. Also see infoq.com/articles/WixSharp.Despair
Thanks @vaccano - I'm using this to handle loading the correct appsettings.environment.json for integration tests. <Target Name="PreBuild" BeforeTargets="PreBuildEvent"> <WriteLinesToFile File="$(TargetDir)\env.config" Lines="$(ConfigurationName)" Overwrite="true"></WriteLinesToFile> </Target>Shortie
A
20

Update

Egors answer to this question ( here in this answer list) is the correct answer.

You can't, not really.
What you can do is define some "Conditional Compilation Symbols", if you look at the "Build" page of you project settings, you can set these there, so you can write #if statements to test them.

A DEBUG symbol is automatically injected (by default, this can be switched off) for debug builds.

So you can write code like this

#if DEBUG
        RunMyDEBUGRoutine();
#else
        RunMyRELEASERoutine();
#endif

However, don't do this unless you've good reason. An application that works with different behavior between debug and release builds is no good to anyone.

Adjoint answered 6/5, 2009 at 12:29 Comment(6)
It may help when developing Windows Services (no need to install / easier debugging)Melany
@Scoregraphic: However with quite different behavior (service vs. command line app)!!!Deedradeeds
Why is conditional expression not finding my custom configuration ? I have code like this: #if WCFDebug /*my code*/ #endif - but it simply doesn't find it. I've added configuration inside settings.Uuge
And what if you have DEV, TEST, QA, PREPROD, PROD ?Appellee
@Appellee Then define conditional compilation symbols for those as well in your project properties.Faison
@Appellee the above answer might have been true several years ago, but modern versions of .net let you get the info. See Egor Novikov's answer below.Manolete
E
10

Conditional Compilation Symbols can by used to achieve this. You can define custom symbols the Properties > Build settings pane for each project, and the use the #if directives to test them in the code.

Example showing how the define the symbol UNOEURO and how to use it in code.

UNOEURO symbol defined here

bool isUnoeuro = false;
#if UNOEURO
    isUnoeuro = true;
#endif
Equipment answered 16/4, 2014 at 5:4 Comment(0)
C
5
  1. Install the SlowCheetah Visual Studio extension.
  2. Right-click on your config file and select 'Add Transform'.

Add Transform

  1. Notice a transform for each build configuration.

Transform for each build configuration

  1. Place a "Build" appSetting into the root config file:
    <?xml version="1.0" encoding="utf-8" ?>
    <configuration>
        <startup> 
          <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.8" />
        </startup>
      <appSettings>
        <add key="Build" value="" />
      </appSettings>
    </configuration>
  1. And place a "Build" directive in each transform:
    <?xml version="1.0" encoding="utf-8"?>
    <!--For more information on using transformations see the web.config examples at http://go.microsoft.com/fwlink/?LinkId=214134. -->
    <configuration xmlns:xdt="http://schemas.microsoft.com/XML-Document-Transform">
      <appSettings>
        <add key="Build" value="Debug" xdt:Transform="Replace" xdt:Locator="Match(key)"/>
      </appSettings>
    </configuration>
  1. Then obtain the "Build" appSetting value in your C# code:

ConfigurationManager.AppSettings["Build"]


Cartography answered 9/1, 2020 at 15:58 Comment(1)
For .Net Standard And Core you can use the .Assembly.GetCustomAttribute<AssemblyConfigurationAttribute>() method. For .NET Framework, the Assembly solution doesn't and the above solution from Jim G. is what I find the best way to get the job done. You don't need the visual studio extension but you need to manipulate the csproj a bit to get it working. You can see a fully detailed way to get it working here : https://mcmap.net/q/64339/-app-config-transformation-for-projects-which-are-not-web-projects-in-visual-studioLap
C
3

You can use a common static method with Conditional Attribute to set the flag to detect DEBUG or RELEASE mode. The SetDebugMode method will be called only when running in the DEBUG mode otherwise it is ignored by Runtime.

public static class AppCompilationConfiguration
{
    private static bool debugMode;

    private static bool IsDebugMode()
    {
        SetDebugMode();
        return debugMode;
    }

    //This method will be loaded only in the case of DEBUG mode. 
    //In RELEASE mode, all the calls to this method will be ignored by runtime.
    [Conditional("DEBUG")]
    private static void SetDebugMode()
    {
        debugMode = true;
    }

    public static string CompilationMode => IsDebugMode() ? "DEBUG" : "RELEASE";

}

You can call it in the code like below

 Console.WriteLine(AppCompilationConfiguration.CompilationMode);
Cashbook answered 24/5, 2019 at 15:45 Comment(0)
F
0

I don't believe you can inject that at compile time into the assembly but one way you could achieve it would be to use MSBuild and add it to the config file of the application.

See this blog post about how to do multi-environment config files using MSBuild - http://adeneys.wordpress.com/2009/04/17/multi-environment-config/

Alternatively you could write an MSBuild task which would edit a certain compiled file (your C# or VB file) and have that run in the BeforeBuild task. It'd be rather tricky as you'd need to work out where to inject it into the file, but provided you had some kind of tokenization set up you should be able to do it. I also doubt it would be pretty!

Flounce answered 6/5, 2009 at 12:36 Comment(0)
S
0

Just as an addition, no matter if you work with "Conditional" or #DebugOrWhatever: If your build configuration contains dots like in "Release.Debug" you have to use "Release_Debug" (with underscore).

Stricken answered 31/1 at 15:29 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.