Trouble using App.Config ConnectionString (String works don't understand code)
I'm using VS2010 on XP.
Below is the app.config file i'm trying to use. I don't understand the part about the connection string. I have two calls to the database that uses this same connection string, but i don't know how to use it.
Code:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<connectionStrings>
<add name="ConnectionString" providerName="System.Data.SqlClient"
connectionString="Data Source = cwsqldb; Initial Catalog =
Annuals; Integrated Security = True" />
</connectionStrings>
<appSettings>
<add key="fromAddress" value="[email protected]"/>
<add key ="ToAddress" value ="[email protected]"/>
<add key="ToBcc" value="[email protected]"/>
<add key="subject" value="codeworth Connection Audit Alert"/>
<add key ="smtp" value="mail88-gwy"/>
</appSettings>
</configuration>
I know I can access the <add key=""> values with the following code.
Code:
string fromAddress = ConfigurationManager.AppSettings["fromAddress"].ToString();
string ToAddress = ConfigurationManager.AppSettings["ToAddress"].ToString();
But how do i access the connection string? I don't understand that block of code AT ALL! I understand that the connection string is composed of different parts. But i've always seen it as basically one long string separated by semicolons.
Thanks for your help!
Re: Trouble using App.Config ConnectionString (String works don't understand code)
OK I think I've figured out how to retrieve the ConnectionString. I'm testing it now.
public static string str = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
However, i must say, i've read tons of articles on the internet about app.config and never once ran across how to do this.
Re: Trouble using App.Config ConnectionString (String works don't understand code)
Since both AppSettings and ConnectionsStrings are both collections derived from ConfigurationElementCollect they'll both work the same. They expose a Item[str] (actually a this[key]) property that allows you to access the item by it's key. To find this in msdn, you need to look at the ConfigurationElementCollection base class and the Item property. It's a bit hard to find, but many collections work this way, so if you see it in the future, you'll know you can access an item using this approach.