Read custom configuration file in C# (Framework 4.0)

我与影子孤独终老i 提交于 2019-11-27 12:02:42
 // Map the roaming configuration file. This
      // enables the application to access 
      // the configuration file using the
      // System.Configuration.Configuration class
      ExeConfigurationFileMap configFileMap =
        new ExeConfigurationFileMap();
      configFileMap.ExeConfigFilename = 
        roamingConfig.FilePath;

      // Get the mapped configuration file.
      Configuration config =
        ConfigurationManager.OpenMappedExeConfiguration(
          configFileMap, ConfigurationUserLevel.None);

from http://msdn.microsoft.com/en-us/library/system.configuration.configurationmanager.aspx

In the past I've used Nini - http://nini.sourceforge.net/manual.php which allows you to read / write custom configuration files (XML / Ini / Registry / .Config) at runtime.

Hope this helps.

My advice with configuration is create your own component to read it.
It may ease the development if at some point you'll decide that you will be getting the configuration from another source like a database or over a web service.
This kind of abstraction also helps you mock the configuration and increases testability (something that the .NET framework doesn't do well at all).
If you are using XML as the configuration format I suggest using Linq to XML.
It's easier to read and use to parse XML files.

nittuj

You can try Cinchoo framework for your needs. It simplifies development work by code first approach. Define a class as below,

namespace HelloWorld
{
    #region NameSpaces

    using System;
    using Cinchoo.Core.Configuration;

    #endregion NameSpaces

    [ChoConfigurationSection("sample")]
    public class SampleConfigSection : ChoConfigurableObject
    {
        #region Instance Data Members (Public)

        [ChoPropertyInfo("name", DefaultValue="Mark")]
        public string Name;

        [ChoPropertyInfo("message", DefaultValue="Hello World!")]
        public string Message;

        #endregion
    }

    static void Main(string[] args)
    {
        SampleConfigSection sampleConfigSection = new SampleConfigSection();
        Console.WriteLine(sampleConfigSection.ToString());
    }

}

First time, when you run the application it will creates the configuration section in [appexename].xml file as below. Then onward any changes made to this file will be picked up automatically

<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <configSections>
    <section name="sample" type="Cinchoo.Core.Configuration.ChoNameValueSectionHandler, Cinchoo.Core, Version=1.0.0.0, Culture=neutral, PublicKeyToken=b7dacd80ff3e33de" />
  </configSections>
  <sample>
    <add key="name" value="Mark" />
    <add key="message" value="Hello World!" />
  </sample>
</configuration>

Or use NameValueCollection easier

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!