2012-03-28 52 views
2

我使用的是Visual Studio 2005,并使用“App.config”文件创建了一个应用程序。 当我尝试编辑和添加新的价值到app.config文件它显示了一个错误,请帮助我..如何在c中配置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" 
+1

请注意,这些'错误'只是信息性消息。 Visual Studio只是让你知道,如果这些值应该是元素,属性,应该存储的类型,那么它就无法解决问题。忽略这些是安全的,但所提供的答案为如何实现读取这些自定义值提供了指导。 – 2012-03-28 17:46:20

回答

6

不要创建“MySettings”组。把你需要的任何东西放在AppSettings组中。

您可以创建一个mySettings组,但是如果您确实包含了自定义(非标准)配置节,则必须将其声明在configSections元素中,如herehere所述。

我会怀疑它是否真的有必要,但是如果除非有很好的理由添加自定义部分,那么我的第一个答案就是我的第一个答案,因为遵循正常标准更好。它只是使未来的维护程序员更容易。

+0

谢谢@DavidStratton .. – Ramesh 2012-03-29 03:50:18

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

还有其他的方法来读取配置文件,但这是徒手输入的简单列表。

+0

加入努力并显示代码。 – David 2012-03-28 14:33:56

+0

谢谢@Dominic Zukiewicz ..对我有用.. – Ramesh 2012-03-29 03:48:06

相关问题