Blue Theme Orange Theme Green Theme Red Theme
 
DevExpress Free UI Controls
Home | Forums | Videos | Advertise | Certifications | Downloads | Blogs | Interviews | Jobs | Beginners | Training
 | Consulting  
Submit an Article Submit a Blog 
 Jump to
Skip Navigation Links
TechnologyExpand Technology
WebsiteExpand Website
Discover the top 5 tips for understanding .NET Interop
Search :       Advanced Search »
Home » XML in C# » How to create config file with xml serialization

How to create config file with xml serialization

This is a simple example of how to use xml serialization to make configuration files.

Page Views : 9981
Downloads : 144
Rating :
 Rate it
Level : Intermediate
   Print Read/Post comments Post a comment  Similar Articles  
   Email to a friend  Bookmark  Author's other articles  
Download Files:
XMLconfigExample.zip
 
 
DevExpress Free UI Controls
Become a Sponsor
 Tag Cloud
 Latest Jobs
More ... 
 Latest Interview Questions
More ... 


This is a simple example of how to use xml serialization to make configuration files.

In many cases there is no need to use
System.Configuration namespace members for application configuration file. This article will focus on XML serialization.

The main idea is to create class which holds configuration data and then, serialize it to a file using XmlSerializer. Classes that can be serialized using XML must be declared as public and have a parameterless constructor. Also serialized members must be public.

For more information about XML serialization please refer to http://msdn.
microsoft.com/en-us/library/182eeyhh.aspx

To serialize and deserialize data use corresponding methods from XmlSerializer class (System.Xml.Serialization). Both of them operate on stream objects.

The following code sample demonstrates creating, reading and saving of simple configuration file.

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

namespace XMLconfigExample
{
    class Program
    {
        static void Main(string[] args)
        {
            // get configuration
            Config.ConfigData config = Config.GetConfigData();

            // use it
            Console.WriteLine(config.buffsize);

            // change data
            config.buffsize = 1024;

            // save config
            Config.SaveConfigData(config);

            // test saved data
            config = Config.GetConfigData();
            Console.WriteLine(config.buffsize);

            Console.ReadKey(true);
        }
    }

    public class Config
    {
        #region Default Data
        private const int DEF_BUFF_SIZE = 2048;
        private const string DEF_LOCAL_GATE_IP = "192.168.2.2";
        private const string DEF_TARGET_IP = "192.168.2.10";
        private static readonly int[] DEF_PORTS = new int[] {
            3500,
            4500,
        };
        #endregion

        // name of the .xml file
        public static string CONFIG_FNAME = "config.xml";

        public static ConfigData GetConfigData()
        {
            if (!File.Exists(CONFIG_FNAME)) // create config file with default values
            {
                using (FileStream fs = new FileStream(CONFIG_FNAME, FileMode.Create))
                {
                    XmlSerializer xs = new XmlSerializer(typeof(ConfigData));
                    ConfigData sxml = new ConfigData();
                    xs.Serialize(fs, sxml);
                    return sxml;
                }
            }
            else // read configuration from file
            {
                using (FileStream fs = new FileStream(CONFIG_FNAME, FileMode.Open))
                {
                    XmlSerializer xs = new XmlSerializer(typeof(ConfigData));
                    ConfigData sc = (ConfigData)xs.Deserialize(fs);
                    return sc;
                }
            }
        }

        public static bool SaveConfigData(ConfigData config)
       
{
            if (!File.Exists(CONFIG_FNAME)) return false; // don't do anything if file doesn't exist

            using (FileStream fs = new FileStream(CONFIG_FNAME, FileMode.Open))
            {
                XmlSerializer xs = new XmlSerializer(typeof(ConfigData));
                xs.Serialize(fs, config);
                return true;
            }
        }

        // this class holds configuration data
        public class ConfigData
        {
            public int buffsize;
            public string local_gate_ip;
            public string target_ip;
            public int[] ports;

            public ConfigData()
            {
                buffsize = DEF_BUFF_SIZE;
                local_gate_ip = DEF_LOCAL_GATE_IP;
                target_ip = DEF_TARGET_IP;
               
ports = DEF_PORTS;
            }
        }
    }
}

This example make/use this config.xml file:

<?xml version="1.0"?>
<ConfigData xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<buffsize>1024</buffsize>
<local_gate_ip>192.168.2.2</local_gate_ip>
<target_ip>192.168.2.10</target_ip>
<ports>
<
int>3500</int>
<int>4500</int>
</ports>
</
ConfigData>

Comment Request!
Thank you for reading this post. Please post your feedback, question, or comments about this post Here.
Login to add your contents and source code to this article
 [Top] Rate this article
 
 About the author
 
Rafal Wozniak
Rafal is a .NET and database developer focused on task automation, client-server, network, distributed applications and mobile technologies. Currently works for Rule Financial as a Software Engineer.
Looking for C# Consulting?
C# Consulting is founded in 2002 by the founders of C# Corner. Unlike a traditional consulting company, our consultants are well-known experts in .NET and many of them are MVPs, authors, and trainers. We specialize in Microsoft .NET development and utilize Agile Development and Extreme Programming practices to provide fast pace quick turnaround results. Our software development model is a mix of Agile Development, traditional SDLC, and Waterfall models.
Click here to learn more about C# Consulting.
 
Introducing MaxV - one click. infinite control. Hyper-V Hosting from MaximumASP.
Finally – a virtual platform that delivers next-generation Windows Server 2008 Hyper-V virtualization technology from a managed hosting partner you can truly depend on. Visit www.maximumasp.com/max for a FREE 30 day trial. Hurry offer ends soon. Climb aboard the MaxV platform and take advantage of High Availability, Intelligent Monitoring, Recurrent Backups, and Scalability – with no hassle or hidden fees. As a managed hosting partner focused solely on Microsoft technologies since 2000, MaximumASP is uniquely qualified to provide the superior support that our business is built on. Unparalleled expertise with Microsoft technologies lead to working directly with Microsoft as first to offer IIS 7 and SQL 2008 betas in a hosted environment; partnering in the Go Live Program for Hyper-V; and product co-launches built on WS 2008 with Hyper-V technology.
Dynamic PDF
ceTE software specializes in components for dynamic PDF generation and manipulation. The DynamicPDF™ product line allows you to dynamically generate PDF documents, merge PDF documents and new content to existing PDF documents from within your applications.
Discover the Top 5 .NET Memory Management Fundamentals
To write the best .NET code, you need to know exactly how the .NET framework really manages memory. Ricky Leeks presents the Top 5 fundamental facts of .NET memory management. Learn more.
Nevron Chart for .NET 2010.1 Now Available
The leading .NET charting control now features PDF, Flash and Silverlight export, visualization of large datasets and more. Deliver true charting functionality to your BI, Scorecard, Presentation or Scientific apps. Download evaluation now.
ASP.NET 4 Hosting
Get 2 Months Free of ASP.NET Hosting for Only $4.95/month! Receive FREE MS SQL and MySQL Databases Including ASP.NET 4/3.5, MVC 3.0, Silverlight 4, Windows 2008/IIS 7.0 Plus FREE IIS 7 Modules. Host UNLIMITED ASP.NET Web Sites – Click Here!
 
 Post a Feedback, Comment, or Question about this article
Subject:
Comment:
Team Foundation Server Hosting
Become a Sponsor
 Comments

 © 2012  contents copyright of their authors. Rest everything copyright Mindcracker. All rights reserved.