Retrieving Data configuration Info

Topics: Data Access Application Block, General discussion
Feb 9, 2007 at 1:57 PM
Hi, I have a big problem.
I have an Data Access Application config section in my app.config, and it works well. But I do need to get back those parameters (User Id, etc) in some way, programatically, to use them somewhere else (I really do not want to have to duplicate configuration info in another section of the app.config).
I have been spending far too much time on this, without finding anything at all. Am I missing something ? Does somebody have any info about this ?

Feb 12, 2007 at 2:21 PM
Could you provide some more detail on the problem? I don't quite understand your question.




David Hayden
Microsoft MVP C#
Feb 12, 2007 at 4:17 PM
I have a connection string in my app.config, and I want to be able to programmatically get all its separate elements (login, user etc) at runtime (since they are used somewhere else).
Even getting back the whole connection string would be quite a good thing at this point, as I would parse it myself to get the individual elements.
Is this clearer ? Do not hesitate telling me if it isn't.
Feb 12, 2007 at 5:44 PM
When using the Data Access Application Block and the Database Class, you can get the connection string associated with the current Database Instance a couple of ways:

Database db = DatabaseFactory.CreateDatabase();
string connectionString = db.ConnectionStringWithoutCredentials;


Database db = DatabaseFactory.CreateDatabase();
string connectionString = null;
using (DbConnection connection = db.CreateConnection())
   connectionString = connection.ConnectionString;

If you want to just get the information about any or all Connection Strings in you application's configuration file you can just read the connectionStrings Section using System.Configuration Functionality:

ConnectionStringSettingsCollection connectionStrings = ConfigurationManager.ConnectionStrings;
foreach (ConnectionStringSettings connection in connectionStrings)
    // Full Connection String
    string connectionString = connection.ConnectionString;
    // Parse the connectionstring
    // Assuming SqlServer Here... Could Get Instance of DbProviderFactory
    SqlConnectionStringBuilder builder = new SqlConnectionStringBuilder(connectionString);
    // Print out Database Name

I am pulling much of this from the top of my head, but it should get you where you want to be.




David Hayden
Microsoft MVP C#