GetOrThrow(string connectionStringName)

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;
var connectionString = ConfigurationManager.ConnectionStrings.GetOrThrow("MyApp");


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.


Double click on the code to select all.