CodeXchange Saturday, December 21, 2024
Home
What's it?
Download
Register
My Snippets
Add Snippet
Search
Faq
Contact Us
Sponsors

Website hosted by


Code Snippet Preview

Review the code snippet before inserting it on your project.

Snippet Metadata
Summary: Read / write settings to config (xml) file.
Language: C#
Author: Robert Wagner
Author snippets RSS:
Culture: en-US
Bytes: 5529
Visual Studio 2005 Snippet:

Snippet Stats
Downloads: 30
Overall rating : 0
Average rating : Snippet rating

Snippet Preview
Code:
/*
    Does not use ConfigurationSettings.AppSettings since it's not supported on 
   .NET Compact Framework and does not support writing settings. 
   
   Uses same schema as app.config file. Example:

      
         
            
            
         
        
   
   Default settings file name is the same as app.config, 
   appends .config to the end of the assembly name. Example:
   
      .config.
*/

using System;
using System.Collections;
using System.Reflection;
using System.Xml;
using System.IO;

namespace SmartClient
{
   /// 
   /// Read / write app.config settings file.
   /// 
   public class Settings
   {
      // internal fields
      Hashtable m_list = new Hashtable();
      string m_filePath = string.Empty;
      bool m_autoWrite = true;
      string[,] m_defaultValues;

      // properties
      
      /// 
      /// Specifies if the settings file is updated whenever a value 
      /// is set. If false, you need to call Write to update the 
      /// underlying settings file.
      /// 
      public bool AutoWrite
      {
         get { return m_autoWrite; }
         set { m_autoWrite = value; }
      }
      
      /// 
      /// Full path to settings file.
      /// 
      public string FilePath
      {
         get { return m_filePath; }
         set { m_filePath = value; }
      }

      /// 
      /// Default constructor. 
      /// 
      public Settings()
      {
         // get full path to file
         m_filePath = GetFilePath();
         
         // populate list with settings from file
         Read();
      }

      /// 
      /// Constructor. Pass in an array of default values.
      /// Sample usage that passes in default values:
      ///
      ///      string[,] values = 
      ///      {
      ///         {"Name", "Live Oak"},
      ///         {"LogEvents", "True"}
      ///      }
      ///
      ///      Settings settings = new Settings(values);
      ///
      /// 
      public Settings(string[,] defaultValues)
      {
         // store default values, use later when populate list
         m_defaultValues = defaultValues;

         // get full path to file
         m_filePath = GetFilePath();

         // populate list with settings from file
         Read();
      }
      

      // public methods
      
      /// 
      /// Set setting value. Update underlying file if AutoUpdate is true.
      /// 
      public void SetValue(string key, object value)
      {
         // update internal list
         m_list[key] = value;
         
         // update settings file
         if (m_autoWrite)
            Write();
      }

      /// 
      /// Return specified settings as string.
      /// 
      public string GetString(string key)
      {
         object result = m_list[key];
         return (result == null) ? String.Empty : result.ToString();
      }
      
      /// 
      /// Return specified settings as integer.
      /// 
      public int GetInt(string key)
      {
         string result = GetString(key);
         return (result == String.Empty) ? 0 : Convert.ToInt32(result);
      }

      /// 
      /// Return specified settings as boolean.
      /// 
      public bool GetBool(string key)
      {
         string result = GetString(key);
         return (result == String.Empty) ? false : Convert.ToBoolean(result);
      }
      
      /// 
      /// Read settings file.
      /// 
      public void Read()
      {
         try
         {
            // first remove all items from list
            m_list.Clear();
            
            // next, populate list with default values
            for (int i=0; i < m_defaultValues.GetLength(0); i++)
               m_list[m_defaultValues[i,0]] = m_defaultValues[i,1];
         
            // last, populate list with items from file
         
            // open settings file
            XmlTextReader reader = new XmlTextReader(m_filePath);

            // go through file and read the xml file and 
            // populate internal list with 'add' elements
            while (reader.Read())
            {
               if ((reader.NodeType == XmlNodeType.Element) && (reader.Name == "add"))
                  m_list[reader.GetAttribute("key")] = reader.GetAttribute("value");
            }
            reader.Close();
         }
         catch (Exception ex)
         {
            System.Diagnostics.Debug.WriteLine(ex.Message);
         }
      }
      
      /// 
      /// Write settings to file.
      /// 
      public void Write()
      {
         try
         {
            // header elements
            StreamWriter writer = File.CreateText(m_filePath);
            writer.WriteLine("");
            writer.WriteLine("\t");

            // go through internal list and create 'add' element for each item
            IDictionaryEnumerator enumerator = m_list.GetEnumerator();
            while (enumerator.MoveNext())
            {
               writer.WriteLine("\t\t",
                  enumerator.Key.ToString(),
                  enumerator.Value);
            }

            // footer elements
            writer.WriteLine("\t");
            writer.WriteLine("");

            writer.Close();
         }
         catch (Exception ex)
         {
            System.Diagnostics.Debug.WriteLine(ex.Message);
         }
      }

      public void RestoreDefaults()
      {
         try
         {
            // easiest way is to delete the file and
            // repopulate internal list with defaults
            File.Delete(FilePath);
            Read();
         }
         catch (Exception ex)
         {
            System.Diagnostics.Debug.WriteLine(ex.Message);
         }
      }


      //
      // private methods
      //
      
      /// 
      /// Return full path to settings file. Appends .config to the assembly name.
      /// 
      private string GetFilePath()
      {
         return Assembly.GetExecutingAssembly().GetName().CodeBase + ".config";
      }
   }
}

Snippet Comments
Comments:
No comments for this snippet

Other snippets that may interest you..
Related Snippets
TDT - GridPage - Page_Init (C#)
CustomValitaor (C#)
(C#)
Get the file extension from a file path or file name (VB.NET)
grab record from db and subtracts it from variable (VB.NET)



Copyright ©2009-2024 CodeXchange. Server version 1.0.3720.32855 Client Version 0.9.0.0

With from Barcelona

Most Helpful members
These are the members who have received the most points for their helpful samples
Zepho Zep
Robert Wagner
Galen Taylor

All time 'Hall of fame'
Formating a file size and adding the B, KB, MB and GB extension appropriately with string.Format (C#)
INI File Access (VB.NET)
Read XML from string into DataSet (C#)
Create Manifest File for your Application (VB.NET)
Round function to avoid banker's rounding (VB.NET)
Get Short and Long Path Names (VB.NET)
Sending Mail through authenticated SMTP server (C#)
One Way Hash for strings (C#)
Formating a file size and adding the B, KB, MB and GB extension appropriately with string.Format (C#)
How do I load an image from a URI address? (VB.NET)
Use our easy to use Visual Studio.NET addin client and start sharing code snippets with the CodeXchange community!
Refreshed: Saturday, December 21, 2024