GetOrThrow(string connectionStringName)
By default, ConfigurationManager.ConnectionStrings returns null if the requested connection string doesn't exist. Use this extension method if you want something a bit more snappy - an exception.
Source
public static string GetOrThrow(this ConnectionStringSettingsCollection connectionStrings, string name)
{
if (String.IsNullOrWhiteSpace(name)) throw new ArgumentException("name was null or empty.", "name");
var connectionString = connectionStrings[name];
if (connectionString == null)
throw new Exception(String.Format("The connection string '{0}' was not found.", name));
return connectionString.ConnectionString;
}
Example
var connectionString = ConfigurationManager.ConnectionStrings.GetOrThrow("MyApp");
Author: Richard Dingwall
Submitted on: 9 dec. 2011
Language: C#
Type: System.Configuration.ConnectionStringSettingsCollection
Views: 5367