Click here to Skip to main content
15,920,632 members
Articles / Programming Languages / C#
Article

Option Library

Rate me:
Please Sign up or sign in to vote.
3.50/5 (6 votes)
1 Aug 2002 88.4K   582   28   15
Provides methods to save and load option classes

Sample Image - OptionLib.jpg

Introduction

I have looked around for a way of saving my application settings, but there are several stumbling blocks. The class should overcome them all. There are only 2 static methods. Load and Save.

Problems

  1. All serializable objects should be serialized.
  2. BinaryFormatter works fine as long as class is not changed in structure.
  3. XmlSerializer do provide methods to serialize classes without a default constructor.

Option class requirements

  • Class MUST have default constructor.
  • An instance of the class must exist before calling Load

Source code

C#
public static void Save(string filename, object options)
{

  Byte[] buffer = new Byte[80];
  MemoryStream ms;
  BinaryFormatter bf = new BinaryFormatter();

  System.Xml.XmlTextWriter xmlwriter = 
    new XmlTextWriter(filename, System.Text.Encoding.Default);

  xmlwriter.Formatting = Formatting.Indented;
  xmlwriter.WriteStartDocument();

  xmlwriter.WriteComment("Option File. Do not edit!");
  xmlwriter.WriteStartElement(options.ToString());
		
  PropertyInfo[] props = options.GetType().GetProperties(
    BindingFlags.Public | 
    BindingFlags.Instance | 
    BindingFlags.SetField);

  foreach (PropertyInfo prop in props)
  {
    xmlwriter.WriteStartElement(prop.Name);

    object da = prop.GetValue(options, null);

    if (da != null) 
    {
      xmlwriter.WriteAttributeString("Value", da.ToString());

      ms = new MemoryStream();
      try 
      {
        bf.Serialize(ms, da);
        ms.Position = 0;
        int count = 0;
        do 
        {
          count = ms.Read(buffer, 0, buffer.Length);
          xmlwriter.WriteBase64(buffer, 0, count);
        }
        while ( count == buffer.Length);
      } 
      catch (System.Runtime.Serialization.SerializationException e)
      {
        Console.WriteLine("SERIALIZATION FAILED: {0}", prop.Name);
      }

    }
    else xmlwriter.WriteAttributeString("Value", "null");

    xmlwriter.WriteEndElement();
  }
  xmlwriter.WriteEndElement();
  xmlwriter.WriteEndDocument();
  xmlwriter.Flush();
  xmlwriter.Close();
}

public static void Load(string filename, object options)
{
  Byte[] buffer = new Byte[80];
  MemoryStream ms;
  BinaryFormatter bf = new BinaryFormatter();

  System.Xml.XmlTextReader reader = new XmlTextReader(filename);

  while (reader.Read())
  {
    switch (reader.NodeType)
    {
      case XmlNodeType.Element:

        if (reader.HasAttributes)
        {
          string name = reader.Name;
          string val = reader.GetAttribute("Value");

          ms = new MemoryStream();
		
          int count = 0;
          do 
          {
            count = reader.ReadBase64(buffer, 0 , buffer.Length);
            ms.Write(buffer, 0,count);
          }
          while (count == buffer.Length);

          ms.Position = 0;

          if (val != "null") 
          {
            try 
            {
              object da = bf.Deserialize(ms);

              Console.Write("Applying {0} : ", name);
              options.GetType().GetProperty(name).SetValue(options, da, null);
              Console.WriteLine("OK");
            }
            catch (System.Runtime.Serialization.SerializationException e)
            {
              Console.WriteLine("FAIL: {0}",e.Message);
            }
          }
        }
        break;
    }
  }
  reader.Close();
}

Implementation

  • static Load(string filename, object optionclass);
  • static Save(string filename, object optionclass);

That's it. Any problems, let me know.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here


Written By
Software Developer
South Africa South Africa
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
GeneralError if Value is 56 character Long Pin
Chandru.BK2-Aug-05 20:27
Chandru.BK2-Aug-05 20:27 
GeneralRe: Error if Value is 56 character Long Pin
leppie2-Aug-05 21:00
leppie2-Aug-05 21:00 
GeneralNice Pin
eirikhm21-Mar-05 5:46
eirikhm21-Mar-05 5:46 
GeneralNice Job Pin
Nick Parker13-Jul-03 3:50
protectorNick Parker13-Jul-03 3:50 
JokeRe: Nice Job Pin
Marcello Miorelli29-Aug-06 22:47
Marcello Miorelli29-Aug-06 22:47 
GeneralReduce Indent Pin
Shog92-Aug-02 5:11
sitebuilderShog92-Aug-02 5:11 
GeneralRe: Reduce Indent Pin
leppie2-Aug-02 6:38
leppie2-Aug-02 6:38 
GeneralRe: Reduce Indent Pin
Shog92-Aug-02 6:41
sitebuilderShog92-Aug-02 6:41 
GeneralRe: Reduce Indent Pin
Paul Watson19-Nov-02 5:55
sitebuilderPaul Watson19-Nov-02 5:55 
GeneralRe: Reduce Indent Pin
Shog919-Nov-02 6:03
sitebuilderShog919-Nov-02 6:03 
GeneralRe: Reduce Indent Pin
peterchen20-Dec-05 7:36
peterchen20-Dec-05 7:36 
GeneralRe: Reduce Indent Pin
Shog920-Dec-05 8:31
sitebuilderShog920-Dec-05 8:31 
GeneralClass changes Pin
Todd Smith2-Aug-02 4:21
Todd Smith2-Aug-02 4:21 
GeneralRe: Class changes Pin
leppie2-Aug-02 6:39
leppie2-Aug-02 6:39 
GeneralRe: Class changes Pin
Member 110857910-Aug-04 15:04
Member 110857910-Aug-04 15:04 

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

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