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





3.00/5 (9 votes)
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
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"/>
</appSettings>
</configuration>
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>This is My EncryptionKey Secret
/PasswordKey>
</ModuleSettings>
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.
GetSettings()
reads the path of Current module's config file name and path from the rootApp.Config
and serializes the config file, typecasts toModuleSettings
type and returns asModuleSettings
.SaveSettings(ModuleSettings settings)
serializes and saves data to the config file!GetSettingsFile()
reads config file namemyAccount_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
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