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 
/>
3
  • 1
    ConfigurationManager.ConnectionStrings["DbConnectionString"] returns an object with those properties. Commented Jan 13, 2020 at 4: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. Commented Jan 13, 2020 at 4:28
  • Also if you use app settings, you can use stackoverflow.com/questions/10766654/… Commented Jan 13, 2020 at 9:33

2 Answers 2

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;
Sign up to request clarification or add additional context in comments.

Comments

0

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

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

lblDBConnName.Text = dbConn.DataSource.ToString();

1 Comment

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.