2

我正在使用 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"
4

2 回答 2

6

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

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

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

于 2012-03-28T14:05:27.190 回答
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);
        }
    }
}

还有其他读取配置文件的方法,但这是徒手键入的最简单方法。

于 2012-03-28T14:13:54.923 回答