Search code examples
c#asp.netconnection-stringconfigsource

Dynamically read the value of configSource from connectionStrings in ASP.NET


I manually change my configSource to point to a local SQL Server or an SQL Azure server, as needed, during development. I would like for my code to find out the value of the configSource so that my code knows what database server is being used.

Using C#, how do I get the current configSource value?

Note that this is not the same as getting the configSource for a Windows application! That way will not work in ASP.NET!


Solution

  • The following code will read the configuration section for connectionStrings out of web.config, and grab the ConfigSource attribute:

    ConnectionStringsSection connectionStringsSection = 
          System.Web.Configuration.WebConfigurationManager
         .GetSection("connectionStrings", "/Web.config") as ConnectionStringsSection;
    string configSource = connectionStringsSection.SectionInformation.ConfigSource;