How to programmatically configure the web.config of a website installed in IIS?

2

I have developed an installer that will add a new website to IIS 7.5. Once the website is created in I would like to configure its connection strings. After the installation the look like this:

<connectionStrings>
    <add name="DefaultConnection" connectionString="$(ReplacableToken_DefaultConnection-Web.config Connection String_0)" providerName="System.Data.SqlClient" />
    <add name="WebContext" connectionString="$(ReplacableToken_WebContext-Web.config Connection String_0)" providerName="System.Data.SqlClient" />
    <add name="ActivityContext" connectionString="$(ReplacableToken_ActivityContext-Web.config Connection String_0)" providerName="System.Data.SqlClient" />
</connectionStrings>

I would like to configure each of them using C#. Here is what I tried:

 using (ServerManager manager = new ServerManager())
     {

         Configuration webConfig = manager.GetWebConfiguration(myWebsite.name);

         ConfigurationSection directoryBrowseSection = webConfig.GetSection("connectionStrings");


         directoryBrowseSection.SetAttributeValue("DefaultConnection", ".\\SQLEXPRESS;Database=_usr;Integrated Security=true");
         directoryBrowseSection.SetAttributeValue("WebContext", ".\\SQLEXPRESS;Database=_main;Integrated Security=true");
         directoryBrowseSection.SetAttributeValue("ActivityContext", ".\\SQLEXPRESS;Database=_activity;Integrated Security=true");
         manager.CommitChanges();

      } 

What I get: Exception Details: System.Runtime.InteropServices.COMException: Invalid index. (Exception from HRESULT: 0x80070585).

The exception is on the following line:

directoryBrowseSection.SetAttributeValue("DefaultConnection", ".\\SQLEXPRESS;Database=_usr;Integrated Security=true");

My question if not clear yet is how do I configure the connection strings on a website installed on IIS using Microsoft.web.administration?

c#
asp.net-mvc
iis
asked on Stack Overflow Aug 4, 2014 by user3320502 • edited Jan 22, 2019 by Cœur

2 Answers

2

I know this post is a little old, but I came across it while looking for something similar. Here's what I came up with:

//using Microsoft.Web.Administration;
var file = "PATH TO FILE";
var configFile = new FileInfo(file);

var virtualDirectoryMapping = new VirtualDirectoryMapping(configFile.DirectoryName, true, configFile.Name);
var webConfigFileMap = new WebConfigurationFileMap();

webConfigFileMap.VirtualDirectories.Add("/", virtualDirectoryMapping);

var webConfig = System.Web.Configuration.WebConfigurationManager.OpenMappedWebConfiguration(webConfigFileMap, "/");

webConfig.ConnectionStrings.ConnectionStrings.Add(new System.Configuration.ConnectionStringSettings("NAME", "CONNECTION STRING"));
webConfig.Save();

In case these help anyone else out there that needs to do anything with a .NET config file (Get the Configuration, pull appSettings or ConnectionString sections):

using System.Configuration;
using System.IO;
using System.Web.Configuration;

namespace YourNamespace
{
    public static class DotNetConfigFile
    {
        public static Configuration GetConfiguration(string filePath)
        {
            if (File.Exists(filePath))
            {
                FileInfo file = new FileInfo(filePath);
                if (file.Name.ToLower() != "web.config")
                {
                    try
                    {
                        ExeConfigurationFileMap map = new ExeConfigurationFileMap() { ExeConfigFilename = filePath };
                        return ConfigurationManager.OpenMappedExeConfiguration(map, ConfigurationUserLevel.None);
                    }
                    catch (ConfigurationErrorsException ex)
                    {
                        return null;
                        //throw;
                    }
                }
                else
                {
                    try
                    {
                        var virtualDirectoryMapping = new VirtualDirectoryMapping(file.DirectoryName, true, file.Name);
                        var webConfigFileMap = new     WebConfigurationFileMap();
                        webConfigFileMap.VirtualDirectories.Add("/",     virtualDirectoryMapping);
                        return WebConfigurationManager.OpenMappedWebConfiguration(webConfigFileMap, "/");
                    }
                    catch(ConfigurationErrorsException ex)
                    {
                        return null;
                        //throw;
                    }
                }
            }
            else
                throw new FileNotFoundException("File not found", filePath);
        }

        public static KeyValueConfigurationCollection GetAppSettings(string filePath)
        {
            var config = GetConfiguration(filePath);
            if (config != null)
                return config.AppSettings.Settings;
            else
                return null;
        }

        public static KeyValueConfigurationCollection GetAppSettings(FileInfo fileInfo)
        {
            return GetAppSettings(fileInfo.FullName);
        }

        public static ConnectionStringSettingsCollection GetConnectionStrings(string filePath)
        {
            var config = GetConfiguration(filePath);
            if (config != null)
                return config.ConnectionStrings.ConnectionStrings;
            else
                return null;
        }

    public static ConnectionStringSettingsCollection GetConnectionStrings(FileInfo fileInfo)
    {
        return GetConnectionStrings(fileInfo.FullName);
    }
}
answered on Stack Overflow Jun 24, 2016 by Alan • edited Jun 24, 2016 by Alan
0

Given the lack of answers and the fact that I could not find a way to do it using microsoft.web.administration, I resorted to reading Web.config from its phyical path. This way I could configure any element I needed in the following fashion:

string[] file = Directory.GetFiles(myWebsite.physicalPath, "*config");
if (file != null)
{
    XmlDocument doc = new XmlDocument();
    doc.Load(file[1]);
    XmlNodeList configurationStrings = doc.SelectNodes("/configuration/connectionStrings/add");
    configurationStrings[0].Attributes["connectionString"].Value = ".\\SQLEXPRESS;Database=_usr;Integrated Security=true";
    configurationStrings[1].Attributes["connectionString"].Value = ".\\SQLEXPRESS;Database=_main;Integrated Security=true";
    configurationStrings[2].Attributes["connectionString"].Value = ".\\SQLEXPRESS;Database=_activity;Integrated Security=true";
    doc.Save(file[1]);
}
answered on Stack Overflow Aug 5, 2014 by user3320502

User contributions licensed under CC BY-SA 3.0