Fetching Connection Strings from App.Config in a Library via ConfigurationManager

Let’s imagine a common situation at work: you’re creating a library that must access a particular database and provide an interface for client applications to retrieve some data.

Easy, right? Simply create a DLL with App.Config, encrypt the connection string, and you’re good to go. Just call ConfigurationManager.ConnectionStrings[...].ConnectionString to get the connection string. If anything changes, you just change the connection string in one place, re-publish the DLL, and all the new consumers will automatically work.

Right?

Wrong! ConfigurationManager doesn’t (easily) allow you to read connection strings from an App.Config file inside a library. To do that, you need to use this workaround (error checking added):

Configuration config = null;
string exeConfigPath = this.GetType().Assembly.Location;

try
{
  string appConfigPath = exeConfigPath.Substring(0, exeConfigPath.LastIndexOf('\\') + 1) + "App.config";
  config = ConfigurationManager.OpenExeConfiguration(exeConfigPath);
}
catch (Exception e)
{
  throw new Exception("Can't read the config file with the connection string. Exception: " + e.Message);
}

if (config != null)
{
  if (!config.HasFile)
  {
    throw new Exception("Config file " + exeConfigPath + " doesn't exist.");
  }

  KeyValueConfigurationElement element = config.AppSettings.Settings["YourConnectionStringName"];
  if (element != null)
  {
    string value = element.Value;
    if (!string.IsNullOrEmpty(value))
    {
      // For some reason, slashes are quoted (eg. \ is converted to \\)
      // De-quote.
      return value.Replace(@"\\", @"\");
    }
  }
  throw new Exception("Found config file, but it doesn't have a value for YourConnectionStringName");
}
else
{
  throw new Exception("Got an empty config file");
}

The meat of this is really the OpenExeConfiguration line, which will open an App.Config file from a DLL (so long as you have the Copy to Output property on it set to Copy Always). You may also need to wrap everything into a <configuration /> tag.

You will also need a reference to System.Configuration in order to use System.Configuration, but I assume you know that already.

About Ashiq Alibhai, PMP

Ashiq has been coding C# since 2005. A desktop, web, and RIA application developer, he's touched ASP.NET MVC, ActiveRecord, Silverlight, NUnit, and all kinds of exciting .NET technologies. He started C# City in order to accelerate his .NET learning.
This entry was posted in Core .NET, Web, Wndows Forms and tagged , , . Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>