【问题标题】:How to access and modify the values of .config file with ini format by using c#?如何使用c#访问和修改ini格式的.config文件的值?
【发布时间】:2015-06-24 16:16:49
【问题描述】:

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

[Menu1]
Enabled=1
Description=Fax Menu 1

[Menu2]
Enabled=1
description=Forms

【问题讨论】:

  • 您的 App 类型到底是什么?您想将这些配置存储在 web.config 中吗?我说的对吗?
  • Reading/writing an INI file 的可能重复项
  • @BrendanGreen 这种情况适用于特定的.ini 文件,但是我想读取.config 文件,它是具有ini 格式的XML 配置文件。跨度>
  • @AliAdl 我的应用类型是 C# Web 表单应用程序。我不想将这些配置存储在web.config 中,因为它已经是一个XML 配置文件。我只想访问/修改这些值。
  • @Alison 上面的文件样本肯定不是 XML。也许您可以通过更新您的问题来澄清?此外,根据你们中的一些其他 cmets - 如果 文件的内容相同,则文件的扩展名无关紧要(iniconfig)。我链接到的副本仍然适用。

标签: c# .net configuration-files


【解决方案1】:

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

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

并将它们检索为:

string userName = WebConfigurationManager.AppSettings["customsetting1"]

如果你想从特定文件中读取。

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

【讨论】:

  • 这里的缺点是在示例中它们为每个菜单项具有多个属性,而不是简单的键值对。如果 OP 想要使用 web.config,他们可能想要创建一些自定义配置部分来适应。 msdn.microsoft.com/en-us/library/2tw134k3(v=vs.140).aspx。否则,只需从文件系统提供 ini 并写回它。
  • 一个问题是我有许多现有的.config filesmenu.config 具有相同的格式。所以我不想将所有值存储到 Web.config 有没有示例方法可以做到这一点? @山
【解决方案2】:

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

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

        }
    }
}

【讨论】:

  • 同样,这种情况只适用于.ini文件,但我的menu文件扩展名是.config
  • @Alison .ini 或 .config 只是一个文件名。没关系。重要的是文件是如何格式化的,并且您正在将文件格式化为 INI 格式。
【解决方案3】:

为了实现集合配置。您可以在 web.config 中使用 ConfigurationSectionConfigurationElementCollection

使用ConfigurationSection 的一个优点是您可以将Menu 配置的物理文件和web.config 配置的其余部分分开。在主机环境上发布应用程序时,这是非常少的。 (见this

首先你需要创建菜单配置类

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

第二定义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);
    }
  }

第三创建高级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>

【讨论】:

  • 这是否意味着我仍需要将这些值存储在 Web.config 中? menu.config 使用 ini 格式,所以我不确定如何读取(访问)它。
  • 如果你想完全保存ini格式你可以使用this question中提到的解决方案
  • 这个答案是你的ini文件的xml等价物
  • 另一个问题:Port = port; ReportType = reportType; 有错误。它表示未定义的变量。我应该在哪里定义它们?您的代码中有一些拼写错误。也许你可以编辑它?
猜你喜欢
  • 2014-03-13
  • 2015-10-06
  • 2012-03-12
  • 1970-01-01
  • 2015-10-02
  • 1970-01-01
  • 1970-01-01
  • 2023-01-19
  • 2013-11-03
相关资源
最近更新 更多