How to access and modify the values of .config file with ini format by using c#?

1.2k Views Asked by At

I have a .config file with ini format called menu.config. I created a C# Web form Application in Visual Studio 2010, and I want to access/modify the values of this file. For example, edit Enable=1 to Enable=2 on [Menu 1]. I have no idea how to start it. Hope someone can give me some suggestions, thank you!

[Menu1]
Enabled=1
Description=Fax Menu 1

[Menu2]
Enabled=1
description=Forms
3

There are 3 best solutions below

2
On BEST ANSWER

I suggest you to store values in Web.config file and retrieve them in all application. U need to store them in app settings

<appSettings>
  <add key="customsetting1" value="Some text here"/>
</appSettings>

and retrieve them as :

string userName = WebConfigurationManager.AppSettings["customsetting1"]

If you want to read from specific file.

Use Server.Mappath for setting path. Following will be the code.

using System;
using System.IO;

class Test
{
    public void Read()
    {
        try
        {
            using (StreamReader sr = new StreamReader("yourFile"))
            {
                String line = sr.ReadToEnd();
                Console.WriteLine(line);
            }
        }
        catch (Exception e)
        {
            Console.WriteLine("The file could not be read:");
            Console.WriteLine(e.Message);
        }
    }
}
4
On

In order to implement collection configuration. You can use ConfigurationSection and ConfigurationElementCollection in your web.config.

One advantage of using ConfigurationSection is that you can separate physical files of Menu configuration and rest of web.config configuration. That is very handful when publishing the app on host environments. (see this)

First you need to create Menu config class

public class MenuConfig : ConfigurationElement
  {
    public MenuConfig () {}

    public MenuConfig (bool enabled, string description)
    {
      Enabled = enabled;
      Description = description;
    }

    [ConfigurationProperty("Enabled", DefaultValue = false, IsRequired = true, IsKey = 

true)]
    public bool Enabled
    {
      get { return (bool) this["Enabled"]; }
      set { this["Enabled"] = value; }
    }

    [ConfigurationProperty("Description", DefaultValue = "no desc", IsRequired = true, 

IsKey = false)]
    public string Description
    {
      get { return (string) this["Description"]; }
      set { this["Description"] = value; }
    }
  }

Second define ConfigurationElementCollection if menu collection

public class MenuCollection : ConfigurationElementCollection
  {
    public MenuCollection()
    {
      Console.WriteLineMenuCollection Constructor");
    }

    public MenuConfig this[int index]
    {
      get { return (MenuConfig)BaseGet(index); }
      set
      {
        if (BaseGet(index) != null)
        {
          BaseRemoveAt(index);
        }
        BaseAdd(index, value);
      }
    }

    public void Add(MenuConfig menuConfig)
    {
      BaseAdd(menuConfig);
    }

    public void Clear()
    {
      BaseClear();
    }

    protected override ConfigurationElement CreateNewElement()
    {
      return new MenuConfig();
    }

    protected override object GetElementKey(ConfigurationElement element)
    {
      return ((MenuConfig) element).Port;
    }

    public void Remove(MenuConfig menuConfig)
    {
      BaseRemove(menuConfig.Port);
    }

    public void RemoveAt(int index)
    {
      BaseRemoveAt(index);
    }

    public void Remove(string name)
    {
      BaseRemove(name);
    }
  }

Third create high level ConfigurationSection that is entry point of your custom configuration

public class MenusConfigurationSection : ConfigurationSection
{
   [ConfigurationProperty("Menus", IsDefaultCollection = false)]
   [ConfigurationCollection(typeof(MenuCollection),
       AddItemName = "add",
       ClearItemsName = "clear",
       RemoveItemName = "remove")]
   public MenuCollection Menus
   {
      get
      {
         return (MenuCollection)base["Menus"];
      }
   }
}

Use the section in web.config

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
   <configSections>
      <section name="MenusSection" type="{namespace}.MenusConfigurationSection, {assembly}"/>
   </configSections>
   <MenusSection>
      <Menus>
         <add Enabled="true" Description="Desc 1" />
         <add Enabled="true" Description="Desc 1" />
      </Menus>
   </ServicesSection>
</configuration>
2
On

This Code Project gives a very straight forward example of how to read an ini file. However as already stated in other examples you really should use the .net app.config system.

http://www.codeproject.com/Articles/1966/An-INI-file-handling-class-using-C

using System;
using System.Runtime.InteropServices;
using System.Text;

namespace Ini
{
    /// <summary>
    /// Create a New INI file to store or load data
    /// </summary>
    public class IniFile
    {
        public string path;

        [DllImport("kernel32")]
        private static extern long WritePrivateProfileString(string section,
            string key,string val,string filePath);
        [DllImport("kernel32")]
        private static extern int GetPrivateProfileString(string section,
                 string key,string def, StringBuilder retVal,
            int size,string filePath);

        /// <summary>
        /// INIFile Constructor.
        /// </summary>
        /// <PARAM name="INIPath"></PARAM>
        public IniFile(string INIPath)
        {
            path = INIPath;
        }
        /// <summary>
        /// Write Data to the INI File
        /// </summary>
        /// <PARAM name="Section"></PARAM>
        /// Section name
        /// <PARAM name="Key"></PARAM>
        /// Key Name
        /// <PARAM name="Value"></PARAM>
        /// Value Name
        public void IniWriteValue(string Section,string Key,string Value)
        {
            WritePrivateProfileString(Section,Key,Value,this.path);
        }

        /// <summary>
        /// Read Data Value From the Ini File
        /// </summary>
        /// <PARAM name="Section"></PARAM>
        /// <PARAM name="Key"></PARAM>
        /// <PARAM name="Path"></PARAM>
        /// <returns></returns>
        public string IniReadValue(string Section,string Key)
        {
            StringBuilder temp = new StringBuilder(255);
            int i = GetPrivateProfileString(Section,Key,"",temp, 
                                            255, this.path);
            return temp.ToString();

        }
    }
}