Click here to Skip to main content
Click here to Skip to main content
Go to top

Read and Write Config Files with an Object Oriented Style with .NET 1.1

, 22 May 2006
Rate this:
Please Sign up or sign in to vote.
Read and Write Config files with an Object Oriented Style with .NET 1.1

Introduction

Hello everyone. Have you ever tried to play with the System.Configuration namespace? I am sure you have tried. You can easily read Settings by the AppSettingsReader. Just couple of lines. But how did you write or save Settings value programmatically? And if I add with an OOP style. You are a great fan of OOP. You want everything object oriented! If you solved the problem already, no NEED to READ this article. If not, go through the code. It is really simple!

The Beginning

Sample image

When I was coding for my thesis project (in ASP.NET), I had seven separate modules for which I had to keep separate Setting/Config files for convenience and reduce dependency on one another. And as it is a Web application, I must be capable of changing config files dynamically. This is because I may not have physical access to the hosting server. Different modules may have different databases! So I needed to be able to read and write contents to my config file.

App.Config File

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
    <appSettings>
        add key="MyAccount_SettingFile" value="ConfigFiles\Accounts.Config"/>

Accounts.Config File

<?xml version="1.0" encoding="utf-8" ?>
<ModuleSettings xmlns:xsi=http://www.w3.org/2001/XMLSchema-instance 
	xmlns:xsd="http://www.w3.org/2001/XMLSchema">
    <ConnectionString>server=(local);database=myDB;uid=sa;pwd=;</ConnectionString>
        //Add < at the beginning and  '>' at end of PassworrKey
    PasswordKey>

Where to Start

Write the ModuleSettings class file. It is a pretty simple class that provides OOP to the moduleSettings:

using System;
using System.Xml;
using System.Xml.Serialization;

namespace myCompany.MyApp.Config
{
    /// <summary>
    /// Summary of ModuleSettings Class
    /// </summary>
    public class ModuleSettings
    {
        private string connectionString;
        private string passwordKey;

        public ModuleSettings()
        { }

        [XmlElement]
        public string ConnectionString
        {
            get 
            {
                return connectionString;
            }
            set 
            {
                connectionString = value;
            }
        }
        [XmlElement]
        public string PasswordKey
        {
            get 
            {
                return passwordKey;
            }
            set 
            {                
                passwordKey = value;
            }
        }
        //Other element goes here
    }
}

In the above code, I declare the elements that I will read from the configuration file and fetch them as XMLElements. The base is ready.

ModuleConfig Class

This is the class that performs most of the activities! There are three static functions in this class.

  1. GetSettings() reads the path of Current module's config file name and path from the root App.Config and serializes the config file, typecasts to ModuleSettings type and returns as ModuleSettings.
  2. SaveSettings(ModuleSettings settings) serializes and saves data to the config file!
  3. GetSettingsFile() reads config file name myAccount_SettingsFile from the applications root or main config file:
using System;
using System.Xml;
using System.IO;
using System.Windows.Forms;
using System.Xml.Serialization;

namespace myCompany.MyApp.Config
{
    /// <summary>
    /// Summary description for ModuleConfig.
    /// </summary>
    public class ModuleConfig
    {
        //No instance can be created for this Class, so make it private
        private ModuleConfig()
        {
            //
            // TODO: Add constructor logic here
            //
        }

        /// <summary>
        /// Get the Setting values from a config file
        /// </summary>
        /// <returns>Module Setting with all settings value</returns>
        public static ModuleSettings GetSettings()
        {
            XmlSerializer serializer=new XmlSerializer(typeof(ModuleSettings));
            ModuleSettings settings=null;
            string filePath = System.IO.Path.Combine
		(System.Windows.Forms.Application.StartupPath , GetSettingsFile());
            
            try
            {
                FileStream fs=new FileStream(filePath,FileMode.Open,FileAccess.Read);    
                //Deserialize the data
                settings=(ModuleSettings)serializer.Deserialize(fs);
                fs.Close();                
            }
            catch(System.IO.FileNotFoundException ex)
            {
                //do something throw exception
                MessageBox.Show(ex.Message);
            }
            return settings;

        }

        public static void SaveSettings(ModuleSettings settings)
        {
            string fileName= System.IO.Path.Combine
		(System.Windows.Forms.Application.StartupPath , GetSettingsFile());
            XmlSerializer seriallizer=new XmlSerializer(typeof(ModuleSettings));
            FileStream fs=new FileStream(fileName,FileMode.Create);
            seriallizer.Serialize(fs,settings);
            fs.Close();
        }
        private static string GetSettingsFile()
        {
            //get the config file name of accounts module from app.config
            string configFileName=
		System.Configuration.ConfigurationSettings.AppSettings
		["MyAccount_SettingFile"];
            return configFileName;
        }        
    }
}

How To Use the Module/Library

If you created a separate class library to read write config (as I did) add a reference to the Class Library. Call the static methods. Get the return values with appropriate object instance and use in your application:

private void btnSaveSettings_Click(object sender, System.EventArgs e)
        {
            //create a new instance of ModuleSettings
            myCompany.MyApp.Config.ModuleSettings newSettings = 
		new myCompany.MyApp.Config.ModuleSettings();
            newSettings.ConnectionString = txtConnectionString.Text.Trim();
            newSettings.PasswordKey = txtKey.Text.Trim();
            // save settings
            myCompany.MyApp.Config.ModuleConfig.SaveSettings(newSettings);
            msg.Visible=true;
            msg.Text = "*Settings Successfully Changed";
            txtConnectionString.Clear();
            txtKey.Clear();
        }    
        private void btnGetSettings_Click(object sender, System.EventArgs e)
        {
            getSettings();
            msg.Visible = true;
            msg.Text = "*Settings Retrieved";
        }
        private void getSettings()
        {
            //Load Settings
            settings = myCompany.MyApp.Config.ModuleConfig.GetSettings();
            txtConnectionString.Text = settings.ConnectionString;
            txtKey.Text = settings.PasswordKey;            
        }

Limitations

As far as I know, this code will work on .NET 1.1. And it may/may not work on .NET 2.0, because in .NET 2.0, the System.Configuration namespace is changed a lot. They do not allow you to write a config file like that. You have to do some tricks. I wish to write about that some other time!

Application of this Code in ASP.NET

If you wish to apply this trick in ASP.NET applications, you have to make some minor changes in the module config class. Like the file path, instead of using... ... you have to map the server path. I leave it as an exercise for you. If you still face difficulties, you are welcome to contact me. For ASP.NET, you can cache some settings (the settings your application frequently uses).

Using Sample Source

Sample image

Unzip the source file. There will be two folders. One is the class library project and another is the winApp project. Go to ReadWriteConfig_src\WinConfigExample -> Double click WinConfigExample.sln, build the solution and see what a simple thing it is!

Conclusion

This example is/will be very helpful if you divide your application into modules and different modules require different configurations. It may happen that you/the user change settings frequently or you keep different databases for different modules and each has a different connection string. Finally, the OOP thing is maintained! Your application is fully Object Oriented. Even the configuration module!

string fileName= System.IO.Path.Combine
	(System.Windows.Forms.Application.StartupPath , GetSettingsFile());

History

  • 22nd May, 2006: Initial post

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Share

About the Author

Syed Moshiur Murshed
Software Developer Pöyry Infra GmbH
Austria Austria
I am Syed Moshiur Murshed from Bangladesh. I studied BSC in Computer Science at American International University Bangladesh(www.aiub.edu). And then MSC in Software Technology at Stuttgart University of Applied Science, Germany(www.hft-stuttgart.de). Currently I am employed as a Software Engineer at Pöyry Infra GmbH in Salzburg, Austria since 04-2011.
I have been learning C# for quite some time and Enjoying it.

Comments and Discussions

 
GeneralWeb.Config in .NET2.0 [modified] PinmemberiNews.COM31-May-06 5:52 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Mobile
Web02 | 2.8.140916.1 | Last Updated 22 May 2006
Article Copyright 2006 by Syed Moshiur Murshed
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid