Read a Value from a Configuration File

One of the best ways to store values and restore them back is Application Configuration File, it is an XML file that you can add from add new element menu , we will se how to take back a value stored in that useful file in this tut so let's start :

1. Add a configuration file to your application:

In the solution explorer Wright click on the solution, choose add-> new Element

Image-1.jpg

From the shown window choose configuration file

Image-2.jpg

Click OK and leave the name as it is .

2. Add a value to the config file

Add the appSettings section and the key and the value like this

<?xml version="1.0" encoding="utf-8" ?>

<configuration>
  <
appSettings>
    <
add key="Mykey "  value=" MyValue "           />
 
</appSettings>
</
configuration>

My Value is the string value we stored in the config file and we will call it later by its key Mykey

3. Get back MyValue stored in my config file :

This the code :

using System;

using System.Collections.Generic;
using
System.ComponentModel;
using
System.Data;
using
System.Drawing;
using
System.Linq;
using
System.Text;
using
System.Windows.Forms;
using
System.Configuration; //must be add as a reference in the references directory

namespace ConfigurationFile

{

    public partial class Form1 : Form

    {
        public Form1()

        {

            InitializeComponent();

        }
 
        private void button1_Click(object sender, EventArgs e)

        {

            MessageBox.Show(ConfigurationManager.AppSettings[0].ToString());

       
}
    }

}

As you see we used the configurationManager to access to the section appSettings and take back our value by the index of the key which is Zero.

Wish you luck, and waiting for any useful comments.

Ebook Download
View all
DevOps
Read by 0 people
Download Now!
Learn
View all