Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to retrieve the databaseName and the serverName from the connectionstring in the webconfig?

Tags:

asp.net

How Do I get the connection string from the Web Config? I want to Display the database and the server name on to my master ASP.net page(C#).

The connection string in my web.config looks:

<add name="Application_ConnectionString" connectionString="Data Source=ServerName;Initial Catalog=DatabaseName;Persist Security Info=True;Connection Timeout =60;Integrated Security=SSPI" providerName="System.Data.SqlClient"/>
like image 752
Talk2me Avatar asked Apr 06 '11 23:04

Talk2me


People also ask

How do you read ConnectionString from configuration file into code behind?

To read the connection string into your code, use the ConfigurationManager class. string connStr = ConfigurationManager. ConnectionStrings["myConnectionString"].

How do I find my ConnectionString?

Right-click on your connection and select "Properties". You will get the Properties window for your connection. Find the "Connection String" property and select the "connection string". So now your connection string is in your hands; you can use it anywhere you want.

Where do I put ConnectionString in web config?

config file in the Views folder.) Find the <connectionStrings> element: Add the following connection string to the <connectionStrings> element in the Web. config file.

How do I get ConnectionString in .NET core?

In ASP.NET Core the configuration system is very flexible, and the connection string could be stored in appsettings. json , an environment variable, the user secret store, or another configuration source. See the Configuration section of the ASP.NET Core documentation for more details.


1 Answers

There's also the SqlConnectionStringBuilder class:

var connectionString = 
  new System.Data.SqlClient.SqlConnectionStringBuilder("Data Source=ServerName;Initial Catalog=DatabaseName;Persist Security Info=True;Connection Timeout =60;Integrated Security=SSPI"); 

Console.WriteLine(connectionString.DataSource);
Console.WriteLine(connectionString.InitialCatalog);
// ...

Response to comment:

To get the connection strings directly from configuration, use:

foreach (ConnectionStringSettings c in System.Web.Configuration.WebConfigurationManager.ConnectionStrings)
{
    var connectionString = new SqlConnectionStringBuilder(c.ConnectionString)
    //connectionString.DataSource; // server name
    //connectionString.InitialCatalog; // database name
}

Note that this will include connection strings in your machine.config (e.g. data source=.\SQLEXPRESS;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|aspnetdb.mdf;User Instance=true). If you don't want to see that you can filter it in code or add a <clear /> element to your web.config before your connection strings.

like image 177
John Rasch Avatar answered Nov 02 '22 20:11

John Rasch