Get Sitecore environment in code

settings cogwheels

I wanted a rendering to spit out different HTML based on environment and I wanted to share one way to do this by using environment transformation configs and sitecore settings.

<configuration xmlns:xdt="http://schemas.microsoft.com/XML-Document-Transform">
   <sitecore>
        <settings>
            <setting name="Environment" value="Dev" 
    xdt:Transform="Replace" xdt:Locator="Match(name)" />
        </settings>
    </sitecore>
</configuration>

Here I would have a config for each environment with a different value for example:

  • EnvironmentSetting.Dev.config
  • EnvironmentSetting.Test.config
  • EnvironmentSetting.Production.config

Now I can get the environment value from this config in code and use it as a condition in an IF statement or Switch Case or whatever you prefer in my code like this:

var environment = Sitecore.Configuration.Settings.GetSetting("Environment", "");

if(environment == "Dev")...

switch(environment)
{ 
  case "Dev":
    <something>
    break;
   ... 

Let me know in the comments how you would use this functionality. Happy coding!

Leave a comment