1

Curious to know if there is a way to read in some parameters of the connectionstring within the web.config file? For example, if I had a Settings page on my website for administrators only, and one of the views within there was to show the name, providerName, and connectionString... could I do this?

<add 
name="DbConnectionString" 
providerName="System.Data.SqlClient" 
connectionString="Data Source=yourservernamehere.net 
/>
Stephen85
  • 250
  • 1
  • 15
  • 1
    `ConfigurationManager.ConnectionStrings["DbConnectionString"]` returns an [object](https://learn.microsoft.com/en-us/dotnet/api/system.configuration.connectionstringsettings) with those properties. – madreflection Jan 13 '20 at 04:24
  • Thanks madrefiection! I thought I was going crazy here, because i had tried this and it didn't work. Another member just let me know that the using system.configuration may not have been declared, which it wasn't. I'll mark this as resolved now. – Stephen85 Jan 13 '20 at 04:28
  • Also if you use app settings, you can use https://stackoverflow.com/questions/10766654/appsettings-get-value-from-config-file – dimmits Jan 13 '20 at 09:33

2 Answers2

4

Curious to know if there is a way to read in some parameters of the connectionstring within the web.config file?

Yes.

For example, if I had a Settings page on my website for administrators only, and one of the views within there was to show the name, providerName, and connectionString... could I do this?

Yes. You can do the same:

using System.Configuration;
string yourConnectionString = ConfigurationManager.ConnectionStrings["yourConnectionStringNameInYourConfigFile"].ConnectionString;
Nguyen Van Thanh
  • 805
  • 9
  • 18
0

First step was to ensure using System.Configuration is declared.

SqlConnection dbConn = new SqlConnection(ConfigurationManager.ConnectionStrings["DbConnectionString"].ToString());

lblDBConnName.Text = dbConn.DataSource.ToString();
Shahid Manzoor Bhat
  • 1,307
  • 1
  • 13
  • 32
Stephen85
  • 250
  • 1
  • 15
  • 1
    Don't use `ToString()` to get the connection string. Use the `ConnectionString` property. It's reasonable that the implementation of `ToString` may change, even if only subtly, but the `ConnectionString` property won't because that's its exact purpose. – madreflection Jan 13 '20 at 04:30