如何使用c#访问和修改ini格式的.config文件的值?

如何使用c#访问和修改ini格式的.config文件的值?,c#,.net,configuration-files,C#,.net,Configuration Files,我有一个ini格式的.config文件,名为menu.config。我在Visual Studio 2010中创建了一个C#Web表单应用程序,我想访问/修改此文件的值。例如,在[菜单1]上编辑Enable=1至Enable=2。我不知道怎么开始。希望有人能给我一些建议,谢谢 [Menu1] Enabled=1 Description=Fax Menu 1 [Menu2] Enabled=1 description=Forms 我建议您将值存储在Web.config文件中,并在所有应用程序中

我有一个ini格式的.config文件,名为
menu.config
。我在Visual Studio 2010中创建了一个C#Web表单应用程序,我想访问/修改此文件的值。例如,在
[菜单1]
上编辑
Enable=1
Enable=2
。我不知道怎么开始。希望有人能给我一些建议,谢谢

[Menu1]
Enabled=1
Description=Fax Menu 1

[Menu2]
Enabled=1
description=Forms

我建议您将值存储在Web.config文件中,并在所有应用程序中检索它们。你需要将它们存储在应用程序设置中

<appSettings>
  <add key="customsetting1" value="Some text here"/>
</appSettings>
如果要从特定文件中读取

使用Server.Mappath设置路径。 下面是代码

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);
        }
    }
}

以实现集合配置。您可以在web.config中使用
ConfigurationSection
ConfigurationElementCollection

使用
ConfigurationSection
的一个优点是,您可以将菜单配置的物理文件与web.config配置的其余部分分开。在主机环境中发布应用程序时,这是非常困难的。(见附件)

首先需要创建菜单配置类

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定义
ConfigurationElementCollection
if菜单集合

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创建高级
ConfigurationSection
,这是自定义配置的入口点

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"];
      }
   }
}
使用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>

此代码项目提供了一个非常简单的示例,说明如何读取ini文件。但是,正如在其他示例中所述,您确实应该使用.net app.config系统

使用系统;
使用System.Runtime.InteropServices;
使用系统文本;
名称空间Ini
{
/// 
///创建新的INI文件以存储或加载数据
/// 
公共类文件
{
公共字符串路径;
[DllImport(“内核32”)]
私有静态外部long WritePrivateProfileString(字符串部分,
字符串键、字符串值、字符串文件路径);
[DllImport(“内核32”)]
私有静态外部int GetPrivateProfileString(字符串部分,
字符串键、字符串定义、StringBuilder retVal、,
int大小,字符串文件路径);
/// 
///文件构造函数。
/// 
/// 
公共文件(字符串INIPath)
{
路径=路径;
}
/// 
///将数据写入INI文件
/// 
/// 
///节名
/// 
///键名
/// 
///值名称
public void IniWriteValue(字符串部分、字符串键、字符串值)
{
WritePrivateProfileString(节、键、值、this.path);
}
/// 
///从Ini文件中读取数据值
/// 
/// 
/// 
/// 
/// 
公共字符串IniReadValue(字符串部分,字符串键)
{
StringBuilder温度=新StringBuilder(255);
int i=GetPrivateProfileString(节,键“”,临时,
255,此.path);
返回温度ToString();
}
}
}

您的应用程序类型到底是什么?是否要将这些配置存储在web.config中?我说的对吗?@BrendanGreen的可能重复情况该案例适用于特定的
.ini
文件,但我想读取
.config
文件,该文件是
ini
格式的XML配置文件。@AliAdl我的应用程序类型是C#Web表单应用程序。我不想将这些配置存储在
web.config
中,因为它已经是一个XML配置文件。我只想访问/修改这些值。@Alison上面的文件示例肯定不是XML。也许你可以澄清一下你的问题?另外,根据您的一些其他评论-如果文件的内容相同,文件的扩展名并不重要(
ini
vs
config
)。我链接到的副本仍然适用。这里的缩进是在示例中,与简单的键值对相比,每个菜单项都有多个属性。如果OP想要使用web.config,他们可能希望创建一些自定义配置部分来适应。否则,只需从文件系统向上提供ini并将其写回即可。一个问题是,我有许多现有的
.config文件
,它们的格式与
菜单.config
相同。所以我不想把所有的值都存储到Web.config中,有什么样的方法可以做到这一点吗@这是否意味着我仍然需要将这些值存储在Web.config中
menu.config
使用
ini
格式,因此我不确定如何读取(访问)它。如果您想准确保存ini格式,您可以使用此答案中提到的解决方案是ini文件的xml等效另一个问题:
Port=Port有错误;ReportType=ReportType。它说的是未定义的变量。我应该在哪里定义它们?你的代码中有一些拼写错误。也许你可以编辑它?同样,这种情况只适用于
.ini
文件,但我的菜单文件扩展名是
.config
@Alison.ini或.config只是一个文件名。没关系。重要的是如何格式化文件,以及您正在以INI格式格式化文件。
<?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>
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();

        }
    }
}