CODEDIGEST
Home Articles CodeDigest Tutorials FAQs
Home > FAQ >  
Technologies
 


How to use App.Config (Application Configuration) in Console Application or Windows Application in C# ?
Submitted By Bala Murugan
On 3/12/2010 7:03:51 AM
Tags: C#,App.Config,Interview Questions  

How to use App.Config (Application Configuration) in Console Application or Windows Application in C# ?


Or


Accessing App.Config Configuration Settings in C#

 

When we develop a console application or windows application, we may require putting the configuration settings in an App.config file similar to Web.config in Asp.net application. You can do this by following the below steps in Visual Studio,


1. Right click your project in Solution explorer.
2. Select "Add New item..".
3. In the "Add New Item.." dialog, select "Application Configuration File" and Click Add.
It will have a content like below,
<?xml version="1.0" encoding="utf-8" ?>
<configuration>

</configuration>


4. You can now add AppSettings and put your config values here. Refer Below,
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <appSettings>
    <add key="smtp" value="cd.smtp.com"/>
    <add key="share" value="\\cdserver.com\share\"/>
    <add key="UserCount" value="2"/>
  </appSettings>
</configuration>


5. Include System.Configuration namespace to access the AppSettings in your code.
You can access the config values through ConfigurationSettings.AppSettings["Your Key"].
Refer the code below,
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Configuration;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            string smtpserver = ConfigurationSettings.AppSettings["smtp"];
            string sharelocation = ConfigurationSettings.AppSettings["share"];
            string usercount = ConfigurationSettings.AppSettings["UserCount"];
            Console.WriteLine(smtpserver);
            Console.WriteLine(sharelocation);
            Console.WriteLine(usercount);
            Console.Read();
        }
    }
}

Recent FAQs
  • View All FAQs..