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"/>
To read the connection string into your code, use the ConfigurationManager class. string connStr = ConfigurationManager. ConnectionStrings["myConnectionString"].
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.
config file in the Views folder.) Find the <connectionStrings> element: Add the following connection string to the <connectionStrings> element in the Web. config file.
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.
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);
// ...
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With