How can I read the value of my VS2010 configuration settings with C#
I have the following se开发者_开发百科ttings:
<ConfigurationSettings>
<Setting name="DstDataConnectionString" value="def" />
<Setting name="SrcDataConnectionString" value="abc" />
</ConfigurationSettings>
Can someone give me advice as to how I can read these settings from my C# program? I've no experience of getting this data so don't really know where to start.
The first thing to do is add the system reference to the project code file:
using System.Configuration;
Then you can pull those settings from the config file across into your c#.
For example, to call my connection string for you database and store it as a string variable:
string sqlconnection = ConfigurationManager.ConnectionStrings["DstDataConnectionString"].ToString()
In this case you the sqlconnection string would store "def".
I generally use appsettings or connectionstrings:
Webconfig:
<appSettings>
<add key="MySetting" value="MyValue"/>
</appSettings>
or
<connectionStrings>
<add name="DbConnection" connectionString="......" ProviderName="System.Data.SqlClient"/>
</connectionStrings>
Code:
using System.Configuration;
ConfigurationManager.AppSettings["MySetting"].ToString();
or
ConfigurationManager.ConnectionStrings["DbConnection"].ConnectionString;
精彩评论