Access Values from App.Config In WPF

No.of Views1177
Bookmarked0 times
Downloads 
Votes0
By  dpatra   On  16 Apr 2010 10:04:18
Tag : WPF , General
we will see how we can access a value from App.Config in WPF Application.
emailbookmarkadd commentsprint

Images in this article missing? We recently lost them in a site migration. We're working to restore these as you read this. Should you need an image in an emergency, please contact us at info@codegain.com

 

Introduction

In this article we will see how we can access a value from App.Config in WPF Application.

Creating WPF Application Project

Fire up Visual Studio 2008 and Create a WPF Application and name the project as ReadWriteConfig. 

Image Loading

Now add a configuration file and name it as App.config. 

Image Loading

After adding the file you need to add the following xml structure.

<configuration>
  <appSettings>
 
  </appSettings>
</configuration>


Now we will add some controls to our Application such as A TextBox for Value and a Button to Add or Update the Value with a key.

 

Image Loading

As you see from the above image the TextBox will carry the user typed Value and when user clicks on the Save Value Button the Value will be created if it doesn’t exists or Update if exists.
First of All we need to take care of the Assemblies we are going to use in our application.

 

Image Loading

As you see from the above image, we need to add System.configuration Assembly reference. Note that by default it is not added when you create an application.
Now add a Key to appsettings with value=””.
 

<configuration>
  <appSettings>
    <add key="UserName" value="" />
  </appSettings>
</configuration>

We need to add a value to the Key through TextBox value. So in the Button click event write the following code.

private void btnUpdate_Click(object sender, RoutedEventArgs e)
        {
            UpdateKey("UserName", txtName.Text);
            txtName.Text = string.Empty;
        }

        public void UpdateKey(string strKey, string newValue)
        {
            XmlDocument xmlDoc = new XmlDocument();
            xmlDoc.Load(AppDomain.CurrentDomain.BaseDirectory + "..\\..\\App.config");

            if (!KeyExists(strKey))
            {
                throw new ArgumentNullException("Key", "<" + strKey + "> does not exist in the configuration. Update failed.");
            }
            XmlNode appSettingsNode = xmlDoc.SelectSingleNode("configuration/appSettings");
            
            foreach (XmlNode childNode in appSettingsNode)
            {
                if (childNode.Attributes["key"].Value == strKey)
                    childNode.Attributes["value"].Value = newValue;
            }
            xmlDoc.Save(AppDomain.CurrentDomain.BaseDirectory + "..\\..\\App.config");
            xmlDoc.Save(AppDomain.CurrentDomain.SetupInformation.ConfigurationFile);
        }

        
        public bool KeyExists(string strKey)
        {
            XmlDocument xmlDoc = new XmlDocument();
            xmlDoc.Load(AppDomain.CurrentDomain.BaseDirectory + "..\\..\\App.config");

            XmlNode appSettingsNode = xmlDoc.SelectSingleNode("configuration/appSettings");
            
            foreach (XmlNode childNode in appSettingsNode)
            {
                if (childNode.Attributes["key"].Value == strKey)
                    return true;
            }
            return false;
        }


But how do we know that the appSetting got modified. So while the window loads the Title will change accordingly to the value stored.

public Window1()
        {
            InitializeComponent();

            if (!string.IsNullOrEmpty(ConfigurationSettings.AppSettings["UserName"]))
            {
                this.Title = ConfigurationSettings.AppSettings["UserName"];
            }
        }

Now run the application and look for the Title Bar. If it displays Window1 then the value of the key is empty.Now update with some value and run the application again.
 

Image Loading

That’s it. We got what we are looking for.Hope this article helps.

Sample Project Source
 

Download source files -45 kb

 

 
Sign Up to vote for this article
 
About Author
 
dpatra
Occupation-Not Provided
Company-Not Provided
Member Type-Expert
Location-Not Provided
Joined date-13 Jul 2009
Home Page-Not Provided
Blog Page-Not Provided
 
 
Other popularSectionarticles
Comments
There is no comments for this articles.
Leave a Reply
Title:
Display Name:
Email:
(not display in page for the security purphase)
Website:
Message:
Please refresh your screen using Ctrl+F5
If you can't read this number refresh your screen
Please input the anti-spam code that you can read in the image.
^ Scroll to Top