.NET Class to Read XML Config File


There are some instances where you may need your dll to have its own .config file. Of course, the .NET framework only uses a config file for the executing assembly (exe's) and not satalite assmeblies (dll's). Here is a class that can be used to read an XML file that follows the .config file schema:

 /// 
 /// Accessor for a configuration file when System.Configuration methods are not supported
 /// 
 /// 
 /// 
 /// [Use Example]
 /// string file = "C:\\config.xml";
 ///
 /// Configuration config = new Configuration(file);
 /// string dbConn = config.AppConfig["dbConn"].ToString()
 ///
 /// SqlConnection conn = new SqlConnection(dbConn);
 /// ...
 ///
 /// [Xml Configuration File Format]
 /// 
 /// 
 ///  
 ///   
 ///   
 ///  
 /// 
 /// 
 /// 
 public class Configuration
 {
  private SortedList _AppConfig;
  private string _FilePath;

  /// 
  /// The full physical file path to the configuration file
  /// 
  public string FilePath
  {
   get { return _FilePath; }
   set { _FilePath = value; }
  }
  /// 
  /// The primary key/value collection of the parsed config file
  /// 
  public SortedList AppConfig
  {
   get { return _AppConfig; }
   set { _AppConfig = value; }
  }

  /// 
  /// Initialize the Configuration class
  /// 
  public Configuration()
  {
   this.FilePath = "config.xml";
   ParseConfigFile();
  }
  /// 
  /// Initialize the Configuration class
  /// 
  /// The full physical path to the configuration file
  public Configuration(string filePath)
  {
   this.FilePath = filePath;
   ParseConfigFile();
  }

  /// 
  /// Parse the configuration file set in the FilePath property.
  /// 
  /// This method is called by the initializer, but should be re-called if the FilePath property is reset.
  public void ParseConfigFile()
  {
   if (File.Exists(this.FilePath))
   {
    XmlDocument xml = new XmlDocument();
    xml.Load(this.FilePath);
    this.AppConfig = new SortedList(xml.GetElementsByTagName("add").Count);

    foreach (XmlNode xnode in xml.GetElementsByTagName("add"))
    {
     this.AppConfig.Add(xnode.Attributes["key"].Value, xnode.Attributes["value"].Value);
    }
   }
   else
   {
    throw new FileNotFoundException("The configuration file '" + this.FilePath + "' could not be found.");
   }
  }

  /// 
  /// Save the configuration settings back to the file set in the FilePath property.
  /// 
  public void SaveConfigFile()
  {
   if (File.Exists(this.FilePath))
   {
    XmlDocument xml = new XmlDocument();
    xml.Load(this.FilePath);
   
    foreach (XmlNode xnode in xml.GetElementsByTagName("add"))
    {
     xnode.Attributes["value"].Value = this.AppConfig[xnode.Attributes["key"].Value].ToString();
    }

    xml.Save(this.FilePath);
   }
  }
 }