Access app.config from a texttemplate

<#@ template debug="false" hostspecific="true" language="C#" #>
<#@ assembly name="System.Core" #>
<#@ assembly name="System.Configuration" #>
<#@ import namespace="System.Linq" #>
<#@ import namespace="System.Text" #>
<#@ import namespace="System.Collections.Generic" #>
<#@ import namespace="System.Configuration" #>
<#@ output extension=".tt.cs" #>
<#
var projectPath = Host.ResolveAssemblyReference("$(ProjectDir)");
var configFile = projectPath + "App.config";
var map = new ExeConfigurationFileMap()
{
    ExeConfigFilename = configFile 
};
Configuration config = ConfigurationManager.OpenMappedExeConfiguration(map, ConfigurationUserLevel.None);
var connectionString = config.ConnectionStrings.ConnectionStrings["<Name>"].ConnectionString;
#>
//<#= connectionString #>

Points to note:

  • hostspecific="true"
  • empty constructor new ExeConfigurationFileMap()
  • thanks to this and this

Post navigation

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.