Maintaining ConnectionSetting and AppSetting in separate files in Visual Studio 2013 application


In this tutorial, i will try to separate database connection settings details and application related settings into separate files than keeping it in Web.config file. To do this, first thing i will do is to open the web application in which i want to create separate files


1. Select the project 
2. Right click on project and select "Add -> Add new item"



3. select "Visual C# -> Web Configuration File" option
4. enter the file name as "ConnectionSettings.config" or file name of your choice. and click on "Add" button



5. Enter the database connection setting details into "ConnectionSettings.config" file as shown below
<?xml version="1.0"?> 
<connectionStrings>
 <add name="db" connectionString="Data Source=VAIO\\MSSQLSERVER2012;User ID=sa;    Password=password1; Initial Catalog=AdventureWorks2008R2;
   Persist Security Info=true;"/>
</connectionStrings>


6. Now we will follow the same steps as followed for "ConnectionSettings.config" to add "Settings.config" file



7. enter the following configuration details in "Settings.config" file
<?xml version="1.0"?> 
<appSettings>
 <add key="welcomeMsg" value="You are welcome to simplyDotnet"/>
</appSettings>

8. Now we need to complete the final step to add the reference to newly added "ConnectionSettings.config" and "Settings.config" file in "Web.config" file:
<connectionStrings configSource="ConnectionSettings.config"></connectionStrings> 
<appSettings configSource="settings.config"/>




9. Add a reference to following namespace in your *.cs file

using System.Configuration;

10. Now we can use following code to read connectionsettings details:

ConfigurationManager.ConnectionStrings["dbConnection"].ToString();

11. We need to use the following code to read appsettings details

 ConfigurationManager.AppSettings["welcomeMsg"].ToString();


  Hope this helps

Comments