如何在c#中配置App.config文件

时间:2012-03-28 14:03:32

标签: c# configuration custom-configuration

我正在使用Visual Studio 2005,并使用“App.config”文件创建了一个应用程序。 当我尝试编辑并向该App.config文件添加新值时,它显示错误,请帮助我..

我的app.config文件包含:

<?xml version="1.0" encoding="utf-8" ?>
 <configuration>
  <appSettings>
   <add key="keyvalue" value="value"/>
    <add key="keyvalue1" value="value1"/>
 </appSettings>
 <mySettings>
   <add name="myname" myvalue="value1"/>
 </mySettings>
</configuration>

它显示错误:

Could not find schema information for the element "mySettings"
Could not find schema information for the element "add"
Could not find schema information for the element "myvalue"

2 个答案:

答案 0 :(得分:6)

不要创建“MySettings”组。在AppSettings组中放置您需要的任何内容。

您可以创建mySettings组,但如果确实包含自定义(非标准)配置部分,则必须按照herehere所述在configSections元素中声明它们。

我会质疑是否真的有必要,然后继续我的第一个答案,除非有一个非常好的理由添加自定义部分,因为它更好地遵循正常标准。它只是让未来的维护程序员更容易。

答案 1 :(得分:3)

您正在定义一个不属于正常配置文件的新部分:

 <mySettings> 
   <add name="myname" myvalue="value1"/> 
 </mySettings> 

要合并您自己的部分,您需要写一些内容来阅读您的特定部分。然后,您可以添加对要处理此部分的处理程序的引用:

<configuration>
    <configSections>
       <section name="mySettings" type="MyAssembly.MySettingsConfigurationHander, MyAssembly"/>
    </configSections>
    <!-- Same as before -->
</configuration>

示例代码示例如下:

public class MySettingsSection
{
     public IEnumerable<MySetting> MySettings { get;set; }
}

public class MySetting
{
    public string Name { get;set; }
    public string MyValue { get;set; }
}

public class MySettingsConfigurationHander : IConfigurationSectionHandler
{
     public object Create(XmlNode startNode)
     {
          var mySettingsSection = new MySettingsSection();

          mySettingsSection.MySettings = (from node in startNode.Descendents()
                                         select new MySetting
                                         {
                                            Name = node.Attribute("name"),
                                            MyValue = node.Attribute("myValue")
                                         }).ToList();

         return mySettingsSection;
     }
}

public class Program
{
    public static void Main()
    {
        var section = ConfigurationManager.GetSection("mySettings") as MySettingsSection;

        Console.WriteLine("Here are the settings for 'MySettings' :");

        foreach(var setting in section.MySettings)
        {
            Console.WriteLine("Name: {0}, MyValue: {1}", setting.Name, setting.MyValue);
        }
    }
}

还有其他方法可以读取配置文件,但这是徒手操作的简单方法。